【问题标题】:Storing Python Program Execution Flow (Function call Flow)存储 Python 程序执行流程(函数调用流程)
【发布时间】:2016-07-20 05:37:41
【问题描述】:

我正在开发一个项目,我必须在其中存储在每个请求-响应周期中调用的所有函数并存储它们。我不需要存储变量的值,我只需要存储我们用它们的参数和它们的执行顺序调用的函数。我正在使用 mongodb 来存储此跟踪。

【问题讨论】:

  • 您可以查看sys.settrace 函数,看看它是否满足您的需求。
  • 有什么理由不使用logging 模块?

标签: python mongodb program-flow


【解决方案1】:

为方便起见,您可以使用函数装饰器。

import functools
import logging

def log_me(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        logging.debug('name: %s, args: %s, kwargs: %s', func.__name__, args, kwargs)                                        
        return func(*args, **kwargs)
    return inner

然后装饰你的函数来记录。

@log_me
def test(x):
    return x + 2

测试调用。

In [10]: test(3)
DEBUG:root:name: test, args: (3,), kwargs: {}
Out[10]: 5

如果您想将条目直接存储在 MongoDB 中,而不是先登录到 logging module,您可以将 logging.debug 行替换为在数据库中创建条目的代码。

【讨论】:

    【解决方案2】:

    sys.settrace 跟踪用于调试的函数,但可以针对此问题进行修改。也许像this -

    import sys
    
    def trace_calls(frame, event, arg):
        if event != 'call':
            return
        co = frame.f_code
        func_name = co.co_name
        if func_name == 'write':
            # Ignore write() calls from print statements
            return
        func_line_no = frame.f_lineno
        func_filename = co.co_filename
        caller = frame.f_back
        caller_line_no = caller.f_lineno
        caller_filename = caller.f_code.co_filename
        print 'Call to %s on line %s of %s from line %s of %s' % \
            (func_name, func_line_no, func_filename,
             caller_line_no, caller_filename)
    

    另见profiling。它描述了程序各个部分执行的频率和时长

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多