1

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

当前目录确实包含:

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 模块的包?当前目录是否总是优先?可以改变吗?

4

1 回答 1

2

您有两个名为l10n. 第一次尝试时import l10n.utils,错误l10n就在路径上。我怀疑这个错误l10n会被 Python shell 缓存,并且在您import l10n.utils第二次尝试时会被咨询(无论您对 所做的更改如何sys.path)。

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

于 2013-03-02T19:17:48.780 回答