Reputation: 3433
I know that __file__
contains the filename containing the code, but is there a way to get the name of the script/file that's calling the function?
If I have a file named filenametest_b.py
:
def printFilename():
print(__file__)
And I import the function in filenametest_a.py
:
from filenametest_b import *
printFilename()
I get:
C:\Users\a150495>python filenametest_a.py
C:\Users\a150495\filenametest_b.py
Is there something I can do in the b
file to print the name of the a
file?
Upvotes: 2
Views: 1406
Reputation: 11
this work for me:
inspect.getouterframes(inspect.currentframe())[1].filename
Upvotes: 0
Reputation: 18675
def printFilename():
import traceback
print traceback.extract_stack()[-2][0]
Upvotes: 0
Reputation: 1121366
You could print sys.argv[0]
to get the script filename.
To get the filename of the caller, you need to use the sys._getframe()
function to get the calling frame, then you can retrieve the filename from that:
import inspect, sys
print inspect.getsourcefile(sys, sys._getframe(1))
Upvotes: 5
Reputation: 3433
Asked a bit too soon, I think I just solved it.
I was just looking around in the inspect
module:
I added this to the filenametest_b.py
file:
def printCaller():
frame,filename,line_number,function_name,lines,index=\
inspect.getouterframes(inspect.currentframe())[1]
print(frame,filename,line_number,function_name,lines,index)
which gives this:
C:\Users\a150495\filenametest_b.py
(<frame object at 0x000000000231D608>, 'filenametest_a.py', 5, '<module>', ['printCaller()\n'], 0)
So this should work.
Upvotes: 0