要跟踪完整的通话记录,也称为'F_BACK'
这是我的代码:
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':
return
caller = frame.f_back
print ('TRACE\t%s\tF_BACK\t%s' % (caller, frame))
return
sys.settrace(trace_calls)
def a():
print("i am A")
def b():
print("i am B")
if __name__ == '__main__':
sys.settrace(trace_calls)
a()
b()
输出:
>TRACE <frame at 0x7f3c14a80650, file '/tmp/test1.py', line 40, code <module>> F_BACK <frame at 0x5587b0ee4050, file '/tmp/test1.py', line 21, code a>
>i am A
>TRACE <frame at 0x7f3c14a80650, file '/tmp/test1.py', line 41, code <module>> F_BACK <frame at 0x5587b0ec3da0, file '/tmp/test1.py', line 24, code b>
>i am B
>TRACE <frame at 0x5587b0ec3da0, file '/tmp/test1.py', line 26, code b> F_BACK <frame at 0x5587b0ee4050, file '/tmp/test1.py', line 21, code a>
>i am A
谢谢。
Python函数不会将C堆栈用于其数据。调用函数时,python创建一个执行框架对象来保存该调用的本地数据。在您的示例中,a()
在调用时创建一个框架对象,这是保存对print
的第一次调用的框架。 a
返回,该帧被释放并返回到堆。下一个调用b()
也创建了一个框架对象,它恰好是在上一行中刚刚释放的那个。它的打印有一个新框架,该框架恰好重用了先前释放的框架的内存。