gpt4 book ai didi

Python sys._getframe

转载 作者:行者123 更新时间:2023-11-30 22:50:36 29 4
gpt4 key购买 nike

/mypath/test.py

import sys

def test():
frame = sys._getframe(0)
f = frame.f_code.co_filename
print('f:', f)
print('co_filename1:', frame.f_code.co_filename)
while frame.f_code.co_filename == f:
frame = frame.f_back
print('co_filename2:', frame.f_code.co_filename)

test()

运行它并得到:

f: /mypath/test.py
co_filename1: /mypath/test.py
Traceback (most recent call last):
File "/mypath/test.py", line 13, in <module>
test()
File "/mypath/test.py", line 9, in test
while frame.f_code.co_filename == f:
AttributeError: 'NoneType' object has no attribute 'f_code'

为什么frame.f_code在while循环中出现NoneType Error,但可以照常打印?谢谢~

最佳答案

每当您运行frame = frame.f_back时,您都会返回到上一个代码帧。然而,当您位于最顶层的帧时,f_back 属性包含 None (如“没有前一帧”) - 因此您应该在该点中断 while 循环。只需添加一个额外的条件即可,例如:

while frame and frame.f_code.co_filename == f:
frame = frame.f_back

关于Python sys._getframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265823/

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