在python中的sys.settrace中打印函数参数

alt*_*ern 8 python

我怎样才能检查sys.settrace调用中函数参数的值?似乎我有可能输出除了参数之外的所有东西(行,文件名,堆栈跟踪,返回值等).是否有一种解决方法可以让我跟踪函数参数值?

mar*_*arc 12

您可以使用代码对象和框架对象的组合.

请参阅Python数据模型参考中有关这些内容的描述.

import sys

def fn(frame, msg, arg):
    if msg != 'call': return
    # Filter as appropriate
    if frame.f_code.co_filename.startswith("/usr"): return
    print("Called", frame.f_code.co_name)
    for i in range(frame.f_code.co_argcount):
        name = frame.f_code.co_varnames[i]
        print("    Argument", name, "is", frame.f_locals[name])

sys.settrace(fn)

def hai(a, b, c):
    print(a, b, c)

hai("Hallo", "Welt", "!")
Run Code Online (Sandbox Code Playgroud)

要意识到的关键是

  1. 我们可以在框架中看到所有局部变量f_locals.
  2. 我们可以从中提取参数列表中变量的名称f_code.co_varnames.