1
/mypath/test.py的Python sys._getframe
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錯誤,但可以打印照常謝謝〜
編碼錯誤。如果* all *堆棧幀在當前文件中(例如,如果直接運行該文件),則循環會從幀堆棧的頂部脫落。此時,「frame == None」。 – dhke