2

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?

1
  • you could probably parse sys.argv[0] Commented Dec 20, 2012 at 22:23

4 Answers 4

5

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))
Sign up to request clarification or add additional context in comments.

1 Comment

inspect.getsourcefile(sys._getframe(1)) works fine. Thanks.
0

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.

Comments

0
def printFilename():
    import traceback 
    print traceback.extract_stack()[-2][0] 

Comments

0

this work for me:

    inspect.getouterframes(inspect.currentframe())[1].filename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.