I want to get the file name / function that called the function being processed.
Use inspect.
caller_file.py
import callee_file
def main():
callee_file.callee_function()
main()
callee_file.py
import inspect
def callee_function():
# print(inspect.stack())
print(inspect.stack()[1].filename)
print(inspect.stack()[1].function)
Calls are stored in inspect.stack in order of slowest call. If you uncomment the 4th line, the following array will be output.
[
FrameInfo(frame=<frame at 0x7fa68460f050, file '/path-to-dir/callee_file.py', line 4, code callee_function>, filename='/path-to-dir/callee_file.py', lineno=4, function='callee_function', code_context=[' print(inspect.stack())\n'], index=0),
FrameInfo(frame=<frame at 0x10cc17650, file 'caller_file.py', line 5, code main>, filename='caller_file.py', lineno=5, function='main', code_context=[' callee_file.callee_function()\n'], index=0),
FrameInfo(frame=<frame at 0x10ca61450, file 'caller_file.py', line 8, code <module>>, filename='caller_file.py', lineno=8, function='<module>', code_context=['main()\n'], index=0)
]
The first is the information on print (inspect.stack ())
on the 4th line of callee_file.py,
The second is the information of callee_file.callee_function ()
on the 5th line of caller_file.py.
The third is the information on main ()
on line 8 of caller_file.py.
Since we want the information of the previous function call, we need ʻinspect.stack () [1] to get the information of the second array. The properties of ʻinspect.stack () [1]
are as follows, but this time it is good if you can get the file name and function name.
Use ʻinspect.stack () [1] .filename, and ʻinspect.stack () [1] .function
.
By the way, you can also get the array number, so you can use ʻinspect.stack () [1] [1], and ʻinspect.stack () [1] [3]
.
https://stackoverflow.com/questions/900392/getting-the-caller-function-name-inside-another-function-in-python
Recommended Posts