模块多次导入 [英] Module imported multiple times
问题描述
第一次加载模块时,我会做一些初始化工作.问题是它以某种方式被导入了两次,我不知道为什么.我认为它可能是通过不同的路径导入的,如本例所示:
I do some init stuff when a module is first loaded. The problem is that somehow it is imported twice, and I can't figure out why. I thought it might be imported using different path, as in this example:
a.py:
from apps.blog import models
...
b.py:
from blog import models
...
我在模块中插入了 print __name __
,并两次打印出了 blog.models
,因此事实证明问题不在导入路径之内.
那么,是否有其他原因可以多次导入一个模块?
I insert print __name__
in my module, and it printed out blog.models
twice, so it turnes out that the problem is not within import paths.
So, is there any other reason for a module to be imported multiple times?
更新:我没有提到我正在使用django.我认为这个问题与Django的manage.py脚本有关: https://docs.djangoproject.com/en/dev/releases/1.4/#updated-default-project-layout-and-manage-py
UPDATE: I didn't mention that I'm using django. I think this problem related to django's manage.py script: https://docs.djangoproject.com/en/dev/releases/1.4/#updated-default-project-layout-and-manage-py
推荐答案
通常,无论绝对引用还是相对引用,Python均不应两次导入模块.Python可能会将源文件视为两个不同的文件,并因此分别导入它们.可能由于符号链接的文件/目录,并排的不同版本或PYTHONPATH中的目录重叠而发生这种情况,这很难说.
Normally Python should not import a module twice regardless of absolute/relative references. It's likely that Python is seeing the source file as two different files and thus importing them separately. This could happen because of symlinked files/directories, or side-by-side different versions, or overlapping directories in PYTHONPATH, it's hard to say.
对此进行追踪的一种方法是使用交互式调试器.添加一行 import pdb;pdb.set_trace()
在文件的顶层,然后在交互式shell中输入 bt
以获得应显示导入链的回溯.继续 c
.再次导入文件并激活调试器后,再次尝试
One way to track this down is to use the interactive debugger. Add a line import pdb; pdb.set_trace()
in the top level of your file, and in the interactive shell enter bt
to get a backtrace which should show the import chain. Continue with c
. When the file is imported a second time and the debugger is activated, try bt
again and compare the two outputs, that may reveal the problem.
这篇关于模块多次导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!