pythonmodulefilepath

In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath?


Without passing it as a parameter...

Ex. In test1.py:

def function():
    print (?????)

and in test2.py

import test1

test1.function()

Is it possible to write ????? so running test2.py prints out 'test2.py' or the full filepath? __file__ would print out 'test1.py'.


Solution

  • This can be achieved using sys._getframe():

    % cat test1.py
    #!/usr/bin/env python
    
    import sys
    
    def function():
        print 'Called from within:', sys._getframe().f_back.f_code.co_filename
    

    test2.py looks much like yours but with the the import fixed:

    % cat test2.py
    #!/usr/bin/env python
    
    import test1
    
    test1.function()
    

    Test run...

    % ./test2.py 
    Called from within: ./test2.py
    

    N.B:

    CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.