how to get the caller's filename, method name in python
You can use the inspect
module to achieve this:
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
filename = module.__file__
Inspired by ThiefMaster's answer but works also if inspect.getmodule()
returns None
:
frame = inspect.stack()[1]
filename = frame[0].f_code.co_filename
Python 3.5+
One-liner
To get the full filename (with path and file extension), use in the callee:
import inspect
filename = inspect.stack()[1].filename
Full filename vs filename only
To retrieve the caller's filename use inspect.stack(). Additionally, the following code also trims the path at the beginning and the file extension at the end of the full filename:
# Callee.py
import inspect
import os.path
def get_caller_info():
# first get the full filename (including path and file extension)
caller_frame = inspect.stack()[1]
caller_filename_full = caller_frame.filename
# now get rid of the directory (via basename)
# then split filename and extension (via splitext)
caller_filename_only = os.path.splitext(os.path.basename(caller_filename_full))[0]
# return both filename versions as tuple
return caller_filename_full, caller_filename_only
It can then be used like so:
# Caller.py
import callee
filename_full, filename_only = callee.get_caller_info()
print(f"> Filename full: {filename_full}")
print(f"> Filename only: {filename_only}")
# Output
# > Filename full: /workspaces/python/caller_filename/caller.py
# > Filename only: caller
Official docs
- os.path.basename(): to remove the path from the filename (still includes the extension)
- os.path.splitext(): to split the the filename and the file extension