Python sys.settrace()方法

Pythonsys.settrace() 方法是向平台的Python解释器注册回溯的一种有效方式。回溯调用是代码中发生事件时返回的信息。

Pythonsys.settrace() 方法的语法

sys.settrace(frame, event, arg)

参数

frame 它代表当前的堆栈帧。
event 字符串数据类型的关键词,如call,line,return,exception, 或opcode. 事件的含义如下。
call :一个函数或一个代码块被调用。
line :一行代码或一个循环即将被执行。
return : 一个函数或一个代码块被返回。
exception :发生了一个异常。
opcode :解释器将执行一个新的操作码。
arg 已经发生的事件的类型。事件有以下参数。
return :要返回的值或没有。
exception :参数是一个由exception,value, 和traceback 组成的元组。

返回

此方法的返回类型是对本地跟踪函数的引用,执行后返回对自身的引用。

示例代码:在Python中使用sys.settrace() 方法

from sys import settrace
def tracer(frame, event, arg = None):
    code = frame.f_code
    func_name = code.co_name
    line_no = frame.f_lineno
    print(f"A {event} has encountered in{func_name}() at the following line number {line_no}. ")
    return tracer
def function():
    return "Python"
def system():
    return function()
settrace(tracer)
system()

输出:

A call has encountered in       system() at the following line number 19.
A line has encountered in       system() at the following line number 20.
A call has encountered in       function() at the following line number 16.
A line has encountered in       function() at the following line number 17.
A return has encountered in     function() at the following line number 17.
A return has encountered in     system() at the following line number 20.

我们在上面的代码中使用了全局跟踪函数来实现本地跟踪函数,该函数返回自身。

示例代码:使用sys.settrace() 方法递归调用一个循环函数

import sys
from sys import settrace
def trace(frame , event, arg):
    code = frame.f_locals["a"]
    if code % 2 == 0:
        frame.f_locals["a"] = code
def f(a):
    print (a)
if __name__ == "__main__":
    sys.settrace(trace)
    for x in range(0,10):
        f(x)

输出:

0
1
2
3
4
5
6
7
8
9

在上面的代码中,我们修改了发给一个函数的参数。该函数使用了一个for 循环,并对指定范围内的数字进行计数。