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:\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?


Answer: 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](http://docs.python.org/2/library/sys.html#sys._getframe) to get the
calling frame, then you can retrieve the filename from that:

    
    
    import inspect, sys
    
    print inspect.getsourcefile(sys, sys._getframe(1))
    

