问题
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 importing it?
回答1:
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.
回答2:
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
.
回答3:
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
回答4:
It can be done by inspecting 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 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
)
来源:https://stackoverflow.com/questions/1457308/how-do-i-find-the-name-of-the-file-that-is-the-importer-within-the-imported-fil