How can I get the name of the script calling the function in python?

Question:

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:Usersa150495>python filenametest_a.py
C:Usersa150495filenametest_b.py

Is there something I can do in the b file to print the name of the a file?

Asked By: Chris Matta

||

Answers:

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))
Answered By: Martijn Pieters

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:Usersa150495filenametest_b.py
(<frame object at 0x000000000231D608>, 'filenametest_a.py', 5, '<module>', ['printCaller()n'], 0)

So this should work.

Answered By: Chris Matta
def printFilename():
    import traceback 
    print traceback.extract_stack()[-2][0] 
Answered By: Andre Holzner

this work for me:

    inspect.getouterframes(inspect.currentframe())[1].filename
Answered By: Ahmad
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.