Python sys._getframe

pup*_*007 2 python

/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()
Run Code Online (Sandbox Code Playgroud)

运行它并得到:

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'
Run Code Online (Sandbox Code Playgroud)

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

jsb*_*eno 6

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

while frame and frame.f_code.co_filename == f:
        frame = frame.f_back
Run Code Online (Sandbox Code Playgroud)