2016-09-01 52 views
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錯誤,但可以打印照常謝謝〜

+0

編碼錯誤。如果* all *堆棧幀在當前文件中(例如,如果直接運行該文件),則循環會從幀堆棧的頂部脫落。此時,「frame == None」。 – dhke

回答

0

每當您運行frame = frame.f_back時,都會回到以前的代碼框。但是,如果您位於最上面的框架中,則f_back屬性包含無(因爲「沒有先前的框架」) - 所以您應該在此時斷開while循環。只需添加一個額外的條件,例如:

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