Python sys._getframe
<p>/mypath/test.py</p>

<pre><code>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()
</code></pre>

<p>run it and get:</p>

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

<p>Why frame.f_code get a NoneType Error in while loop but can print as usual?Thanks~</p>

<p>Whenever you run <code>frame = frame.f_back</code> you go back to the previous code frame. When you are on the topmost frame, however, <code>f_back</code> attribute contains None (as in "there is no previous frame") - so you should just break off the while loop at that point. Just add an extra  condition to that, for example:</p>

<pre><code>while frame and frame.f_code.co_filename == f:
        frame = frame.f_back
</code></pre>

python