gpt4 book ai didi

python settrace for 循环

转载 作者:行者123 更新时间:2023-12-01 05:55:03 24 4
gpt4 key购买 nike

我对跟踪 for 循环的执行感兴趣。具体来说,我想在 for 循环退出时在屏幕上打印一条消息。需要注意的是,我无法控制 for 循环,也就是说,其他人会将我的代码传递给 for 循环进行跟踪。这是一些示例代码:

import sys
import linecache

def trace_calls(frame, event, arg):
if event != 'call':
return
co = frame.f_code
func_name = co.co_name
if func_name == 'write':
return
return trace_lines

def trace_lines(frame, event, arg):
if event != 'line':
return
co = frame.f_code
line_no = frame.f_lineno
filename = co.co_filename
print("%d %s"%(line_no, linecache.getline(filename, line_no)[:-1]))

def some_elses_code():
j = 0
for i in xrange(0,5):
j = j + i
return j

if __name__ == "__main__":
sys.settrace(trace_calls)
some_elses_code()

代码的输出:

22     j = 0
23 for i in xrange(0,5):
24 j = j + i
23 for i in xrange(0,5):
24 j = j + i
23 for i in xrange(0,5):
24 j = j + i
23 for i in xrange(0,5):
24 j = j + i
23 for i in xrange(0,5):
24 j = j + i
23 for i in xrange(0,5):
25 return j

我知道我可以只查看行号,看看已执行的行不是下一行,但这感觉不对。我想检查传递到trace_lines方法的框架对象,并查看for循环中使用的迭代器没有更多项目。 This link说 for 循环捕获异常,然后它知道迭代器已全部用完,但我看不到框架对象上填充的任何异常对象(即,frame.f_exc_value 始终为 None)。此外,我在本地范围内没有看到 var 是 for 循环中使用的迭代器。这样的事情可能吗?

最佳答案

for 循环创建的迭代器是循环私有(private)的,并保存在 Python 堆栈中,left there通过 GET_ITERpicked up每次执行 FOR_ITER 时,这就是为什么您在本地人中看不到它。

FOR_ITER 确实通过捕获迭代器引发的 StopIteration 来终止循环,但这已通过 directly checking whether tp_iternext returned NULL 进行了测试。 ,因此异常在有机会传播到 Python 框架之前就被捕获并清除。但即使您有权访问迭代器,您也无能为力,因为 Python 迭代器不支持查看。

由于 Python 的跟踪机制在输入或离开 for block 时不会调用跟踪回调,因此您似乎需要采取一些技巧,例如处理 line 事件发现循环已退出。

关于python settrace for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com