debugging – filename and line number of Python script
debugging – filename and line number of Python script
Thanks to mcandre, the answer is:
#python3
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe())
print(frameinfo.filename, frameinfo.lineno)
Whether you use currentframe().f_back
depends on whether you are using a
function or not.
Calling inspect directly:
from inspect import currentframe, getframeinfo
cf = currentframe()
filename = getframeinfo(cf).filename
print This is line 5, python says line , cf.f_lineno
print The filename is , filename
Calling a function that does it for you:
from inspect import currentframe
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
print This is line 7, python says line , get_linenumber()
debugging – filename and line number of Python script
Handy if used in a common file – prints file name, line number and function of the caller:
import inspect
def getLineInfo():
print(inspect.stack()[1][1],:,inspect.stack()[1][2],:,
inspect.stack()[1][3])