挂钩 Python 中的每个函数调用

2024-02-18

我有一个庞大的代码库,其中包含数千个函数。

我想在每次函数调用之前和之后、函数启动和结束时启用代码执行。

有没有一种方法可以在不重新编译 Python 或向每个函数添加代码的情况下完成此操作?有没有办法挂钩我的代码中的每个函数调用?


是的,您可以使用sys.settrace() https://docs.python.org/3/library/sys.html#sys.settrace or sys.setprofile() https://docs.python.org/3/library/sys.html#sys.setprofile注册回调和句柄的函数'call'也许'return'事件。然而,这会大大减慢你的代码速度。调用函数有开销,为每个函数调用添加另一个函数调用会增加更多开销。

默认情况下,sys.settrace()hook 仅在调用时调用(其中call指示正在输入的新作用域,包括类体和列表、字典和集合推导式,以及生成器表达式),但您可以选择返回要为刚刚输入的作用域调用的跟踪函数。如果您只对通话感兴趣,请返回None从跟踪功能。请注意,这使您可以选择收集更多信息的范围。sys.settrace()仅报告 Python 代码,而不报告内置可调用对象或已编译扩展中定义的可调用对象。

The sys.setprofile()对 Python 函数和内置函数以及编译的扩展对象的调用都会调用 hook,并且每当调用返回或引发异常时也会调用相同的回调。不幸的是,无法区分 Python 函数的返回值None或提出异常。

在这两种情况下,您都会获得当前的frame https://docs.python.org/3/reference/datamodel.html#frame-objects,以及事件名称和arg,通常设置为None但对于一些更具体的事件:

def call_tracer(frame, event, arg):
    # called for every new scope, event = 'call', arg = None
    # frame is a frame object, not a function!
    print(f"Entering: {frame.f_code.co_name}")
    return None

sys.settrace(call_tracer)

使用时sys.settrace()返回一个函数对象而不是None允许您跟踪框架内的其他事件,这是“本地”跟踪功能。您可以为此重复使用相同的函数对象。这会进一步减慢速度,因为现在您正在为每一行源代码调用一个函数。然后调用本地跟踪函数'line', 'exception' and 'return'事件,但您可以通过设置禁用每行事件frame.f_trace_lines = False(需要 Python 3.7 或更高版本)。

这是两个钩子的简短演示(假设使用 Python 3.7 或更高版本);它忽略异常事件选项:

import sys

# demo functions, making calls and returning things

def foo(bar, baz):
    return bar(baz)

def spam(name):
    print(f"Hello, {name}")
    return [42 * i for i in range(17)]

# trace functions, one only call events, another combining calls and returns

def call_tracer(frame, event, arg):
    # called for every new scope, event = 'call', arg = None
    # frame is a frame object, not a function!
    print(f"Entering: {frame.f_code.co_name}")
    return None

def call_and_return_tracer(frame, event, arg):
    if event == 'call':
        print(f"Entering: {frame.f_code.co_name}")
        # for this new frame, only trace exceptions and returns
        frame.f_trace_lines = False
        return call_and_return_tracer
    elif event == 'c_call':
        print(f"Entering: {arg.__name__}")
    elif event == 'return':
        print(f"Returning: {arg!r}")
    elif event == 'c_return':
        print(f"Returning from: {arg.__name__}")

if __name__ == '__main__':
    sys.settrace(call_tracer)
    foo(spam, "world")
    print()

    sys.settrace(call_and_return_tracer)
    foo(spam, "universe")
    print()
    sys.settrace(None)

    sys.setprofile(call_and_return_tracer)
    foo(spam, "profile")

运行此输出:

Entering: foo
Entering: spam
Hello, world
Entering: <listcomp>

Entering: foo
Entering: spam
Hello, universe
Entering: <listcomp>
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]

Entering: foo
Entering: spam
Entering: print
Hello, profile
Returning from: print
Entering: <listcomp>
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]
Returning: [0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420, 462, 504, 546, 588, 630, 672]
Returning: None

如果可以更改代码,请仅将装饰器添加到要跟踪的函数中,这样就可以限制开销。如果您准备编写一些代码来进行更改,您甚至可以自动化此操作;与ast module https://docs.python.org/3/library/ast.html您可以将代码解析为可以转换的对象树,包括添加@decorator句法。这不是that简单,但如果您的代码库很大,那么确实值得。请参阅绿树蛇项目 https://greentreesnakes.readthedocs.io/en/latest/有关如何执行此操作的更深入的文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

挂钩 Python 中的每个函数调用 的相关文章

随机推荐