问题描述
如何在 python 中找出哪个文件正在导入特定文件?
How can I find out what file is importing a particular file in python?
考虑以下示例:
#a.py
import cmn
....
#b.py
import cmn
...
#cmn.py
#Here, I want to know which file (a.py or b.py)
#is importing this one.
#Is it possible to do this?
...
a.py
、b.py
和 cmn.py
的所有文件都在同一个目录下.
All the files a.py
, b.py
and cmn.py
are in the same directory.
我为什么要这样做?
在 C/C++ 中,它们具有包含特性.我想做的事情可以通过C/C++代码来说明.
Why do I want to do this?
In C/C++, they have include feature. What i want to do can illuminate by the C/C++ code.
//a.cpp
....
#define SOME_STUFF ....
#include "cmn.h"
//b.cpp
...
#define SOME_STUFF ....
#include "cmn.h"
//cmn.h
//Here, I'll define some functions/classes that will use the symbol define
//in the a.cpp or b.cpp
...
....code refer to the SOME_STUFF.....
在 C/C++ 中,我们可以使用这种方法来重用源代码.
In C/C++, we can use this method to reuse sourecode.
现在回到我的python代码.
当 a.py 导入 cmn.py 时,我希望运行 cmn.py 并且 cmn.py 将引用 a.py.
中定义的符号b.py导入cmn.py时,希望运行cmn.py,cmn.py会引用b.py中定义的符号.
Now return to my python code.
When a.py import cmn.py, i hope to run cmn.py and the cmn.py will refer to the symbol defined in the a.py.
When b.py import cmn.py, i hope to run cmn.py and the cmn.py will refer to the symbol defined in the b.py.
推荐答案
collections 模块中的 namedtuple 代码有一个示例说明如何(以及何时)执行此操作:
The namedtuple code in the collections module has an example of how (and when) to do this:
#cmn.py
import sys
print 'I am being imported by', sys._getframe(1).f_globals.get('__name__')
这种方法的一个限制是最外层的模块总是被命名为 __main__
.如果是这种情况,则可以从 sys.argv[0]
确定最外层模块的名称.
One limitation of this approach is that the outermost module is always named __main__
. If that is the case, the name of the outermost module can be determined from sys.argv[0]
.
第二个限制是,如果使用 sys._getframe 的代码在模块范围内,它只会在 cmn.py 的第一次导入时执行.如果要监视模块的所有导入,则需要在导入后调用某种函数.
A second limitation is that if the code using sys._getframe is in the module scope it is only executed on the first import of cmn.py. You'd need to call a function of some sort after imports if you want to monitor all imports of the module.
这篇关于如何知道谁在 python 中导入我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论