Reputation: 423
I'm writing a Python 3.4 script. In the directory I have:
main.py
core.py
In main.py
I have:
import core
print(core.status())
In core.py
I have:
def status():
return filename
Which I want the filename
which imported core.status()
. Here is filename='main.py'
because I use core.status()
in lots of files, it is not good to use __main__
.
Is it possible to catch the filename which imported another function and print it inside the function as I explained above?
Upvotes: 1
Views: 103
Reputation: 26698
To get the filename of the caller, you can use psutil
import psutil
def status():
callee = psutil.Process()
caller = psutil.Process(callee.ppid())
return caller.cmdline()
Or sys.exc_info
:
import sys
def status():
print sys.exc_info()[2].tb_frame.f_code.co_filename
Upvotes: 1
Reputation: 20928
You can extract this from the stack trace:
import traceback
def status():
print(traceback.extract_stack(limit=2)[-2][0])
-2
just means the second last entry of the stack, i.e. what called status()
.
I'm guessing what you mean by import is to call.
Upvotes: 1