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

被刻印的时光 ゝ 提交于 2020-07-09 03:09:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!