Skip to content Skip to sidebar Skip to footer

How Do I Find The Name Of The File That Is The Importer, Within The Imported File?

How do I find the name of the file that is the 'importer', within the imported file? If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file impo

Solution 1:

Use

sys.path[0]

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

See Python Path Issues

Solution 2:

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

import traceback

and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its importer, etc. recursively) are all on the callstack.

Solution 3:

It can be done by inspecting the stack:

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

But inspecting the stack can be buggy. Why do you need to know where a file is being imported from? Why not have the file that does the importing (a.py and b.py) pass in a name into c.py? (assuming you have control of a.py and b.py)

Solution 4:

That's why you have parameters.

It's not the job of c.py to determine who imported it.

It's the job of a.py or b.py to pass the variable __name__ to the functions or classes in c.py.

Post a Comment for "How Do I Find The Name Of The File That Is The Importer, Within The Imported File?"