Friday, April 22, 2011

[Level 2] How to display current line number in Python

If you want to display current line number for debug info.
You can import inspect to do that.
#!/bin/env python
import inspect
from inspect import currentframe, getframeinfo

def getFilenameLineno():
    frameinfo = getframeinfo(currentframe().f_back)
    return (frameinfo.filename, frameinfo.lineno)

def lineno():
    return inspect.currentframe().f_back.f_lineno

def curr_filename_lineno():
    return inspect.currentframe().f_back.f_code

if __name__ == '__main__':
    print lineno()
    # skip line with comment
    print curr_filename_lineno()
    
    print '%s(#%s)' % getFilenameLineno()

    print lineno()

$ ./testLineno.py 
16
<code object <module> at 0xb7509f50, file "/tmp/t.py", line 2>
/tmp/testLineno.py(#20)
22

Another way is to parse inspect.stack()
e.g.
#!/bin/env python
import inspect

def t():
    tt()

def tt():
    ttt()

def ttt():
    tttt()

def tttt():
    print inspect.stack()

if __name__ == '__main__':
    t()

$ ./test.py 
[(<frame object at 0x18ff820>, '/tmp/t.py', 14, 'tttt', ['    print inspect.stack()\n'], 0), (<frame object at 0x190d970>, '/tmp/t.py', 11, 'ttt', ['    tttt()\n'], 0), (<frame object at 0x18fe0c0>, '/tmp/t.py', 8, 'tt', ['    ttt()\n'], 0), (<frame object at 0x1924460>, '/tmp/t.py', 5, 't', ['    tt()\n'], 0), (<frame object at 0x18c7f70>, '/tmp/t.py', 17, '<module>', ['    t()\n'], 0)]

more info, please reference here.

Wish this helps. regards, Stanley Huang