How can I get the file name and line number in python script.
Exactly the file information we get from an exception traceback. In this case without raising an excep
import inspect
file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]
#Try printing inspect.stack() you can see current stack and pick whatever you want
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()