导入优先级一致性?

时间:2013-03-02 19:09:15

标签: python

我在导入模块时对优先级感到困惑,如何更改它。

当前目录包含:

l10n/__init__.py
l10n/moneyfmt.py

另一个包含额外包的目录(与当前不同)确实包含:

/opt/l10n/__init__.py
/opt/l10n/utils.py

现在运行python交互式解释器:

>>> import sys
>>> sys.path
['', '/usr/lib/python27.zip', '/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload',
'/usr/lib/python2.7/site-packages', '/usr/lib/python2.7/site-packages/PIL',
'/usr/lib/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages/setuptools-0.6c11.egg-info']
>>> import l10n.utils
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named utils    # CORRECT, NOT IN PATH YET
>>> sys.path.insert(0, '/opt')
>>> sys.path
['/opt', '', '/usr/lib/python27.zip', '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7/site-packages',
 '/usr/lib/python2.7/site-packages/PIL',
 '/usr/lib/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages/setuptools-0.6c11.egg-info']
>>> import l10n.utils
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named utils    # WHY IT CAN NOT FIND THE MODULE?

为什么在我在sys.path中预先填写搜索路径的完整路径之后找不到包含l10n.utils模块的包?当前目录始终是否优先使用?可以改变吗?

1 个答案:

答案 0 :(得分:2)

您有两个名为l10n的模块。第一次尝试import l10n.utils时,错误的l10n就在路径上。我怀疑这个错误l10n正在被Python shell缓存,并且当你第二次尝试import l10n.utils时会被咨询(无论你对sys.path做出了什么改变)。< / p>

尝试重新启动Python shell,首先更改sys.path,然后立即执行import l10n.utils