跟踪时获取 python 内置函数的返回值

M. *_*ber 5 python debugging trace profiling

通过使用sys.setprofile (profilefunc),我不仅可以跟踪常规 Python 函数,还可以通过事件“c_call”和“c_return”跟踪内置函数,但我找不到获取内置函数的返回值的方法。

对于常规函数,arg传递给 profilefunc 的参数 指的是返回值(如果event等于“return”)。但是,如果event等于“c_return”,arg则为 C 函数对象。

是否有另一种方法来检索内置函数的返回值?也许通过从帧中提取最后返回的值?

这是一个最小的例子:

import sys
import numpy as np
from types import FrameType


def tracefunc(frame: FrameType, event: str, arg):
    if event == 'call':
        func_name = frame.f_code.co_name
        print(f'Call_to {func_name}')
    elif event == 'return':
        func_name = frame.f_code.co_name
        print(f'Return_from {func_name}, returning {arg}')
    elif event == 'c_call':
        func_name = arg.__name__
        print(f'Call_to_builtin {func_name}')
    elif event == 'c_return':
        func_name = arg.__name__
        print(f'Return_from_builtin {func_name}, returning ???')
    return tracefunc


if __name__ == '__main__':
    sys.setprofile(tracefunc)
    # non-builtin function
    foo = [x + 1 for x in [1, 2]]
    # builtin function
    bar = np.random.uniform()
    sys.setprofile(None)
Run Code Online (Sandbox Code Playgroud)

随着输出

Call_to <listcomp>
Return_from <listcomp>, returning [2, 3]
Call_to_builtin uniform
Return_from_builtin uniform, returning ???
Call_to_builtin setprofile
Run Code Online (Sandbox Code Playgroud)