I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how.
How to get those info with inspect? Or is there any other way to get the info?
import inspect
print __file__
c=inspect.currentframe()
print c.f_lineno
def hello():
print inspect.stack
?? what file called me in what line?
hello()
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The caller’s frame is one frame higher than the current frame. You can use inspect.currentframe().f_back to find the caller’s frame.
Then use inspect.getframeinfo to get the caller’s filename and line number.
import inspect
def hello():
previous_frame = inspect.currentframe().f_back
(filename, line_number,
function_name, lines, index) = inspect.getframeinfo(previous_frame)
return (filename, line_number, function_name, lines, index)
print(hello())
# ('/home/unutbu/pybin/test.py', 10, '<module>', ['hello()n'], 0)
Method 2
I would suggest to use inspect.stack instead:
import inspect
def hello():
frame,filename,line_number,function_name,lines,index = inspect.stack()[1]
print(frame,filename,line_number,function_name,lines,index)
hello()
Method 3
I published a wrapper for inspect with simple stackframe addressing covering the stack frame by a single parameter spos:
E.g. pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)
where spos=0 is the lib-function, spos=1 is the caller, spos=2 the caller-of-the-caller, etc.
Method 4
If the caller is the main file, simply use sys.argv[0]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0