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()

$ ./ 
<code object <module> at 0xb7509f50, file "/tmp/", line 2>

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

def t():

def tt():

def ttt():

def tttt():
    print inspect.stack()

if __name__ == '__main__':

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

more info, please reference here.

Wish this helps. regards, Stanley Huang