How do I find the name of the importer file in the imported file?

How do I find the name of the file that is the importer in the imported file?

If a.py

u b.py

import c.py

, is there anyway that c.py can know the name of the file importing it?

+2


source to share


4 answers


At the top level of c.py (i.e. outside of any function or class), you should get the information you need by running

import traceback

      



and then consider the result of traceback.extract_stack (). At the time the top-level code is executed, the module importer (and its importer, etc., recursively) are frozen.

+1


source


This is why you have parameters.

This is not a task c.py

to determine who imported it.



Task a.py

or b.py

pass a variable __name__

to functions or classes in c.py

.

+2


source


This can be done by checking the stack:

#inside c.py:
import inspect
FRAME_FILENAME = 1
print "Imported from: ", inspect.getouterframes(inspect.currentframe())[-1][FRAME_FILENAME]
#or:
print "Imported from: ", inspect.stack()[-1][FRAME_FILENAME]

      

But checking the stack can be a mistake. Why do you need to know where the file is being imported from? Why not upload a file that imports ( a.py

and b.py

) name c.py

? (assuming you have control over a.py

and b.py

)

+1


source


Using

sys.path [0]

returns the path to the script that the python interpreter started. If you can use this script directly, it will return the path to the script. If the script, however, was imported from another script, it will return the path to that script.

See Python Path Issues

+1


source







All Articles