存储Python程序执行流程(函数调用流程)

Storing Python Program Execution Flow (Function call Flow)

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

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

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 行替换为在数据库中创建条目的代码。

sys.settrace traces a function for debugging but can be modified for this problem. Maybe something like 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。它描述了程序各部分执行的频率和时长