为什么Python`主管道(['install',…])`give ImportError,但仅适用于带点的包名?

2024-05-16 05:49:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当运行以下代码(python2.7.12,在Linux上使用sudo -H)时,从包'plaitpy'和'巴森银行'从未安装过

import sys
import os

# The following code successfully installs bda.basen, then fails to import it.
# However, it works for plaitpy (a random recently updated package).

assert '/usr/local/lib/python2.7/dist-packages' in sys.path

import pip
pip.main(['install', 'plaitpy', 'bda.basen'])

assert '/usr/local/lib/python2.7/dist-packages' in sys.path

assert os.path.isfile('/usr/local/lib/python2.7/dist-packages/plaitpy/__init__.py')
import plaitpy # this succeeds, as expected
print plaitpy 

assert os.path.isfile('/usr/local/lib/python2.7/dist-packages/bda/basen/__init__.py')
import bda.basen # THIS FAILS WITH 'ImportError: No module named bda.basen'
print bda.basen

最后一条import语句将以ImportError: No module named bda.basen失败。在

根据一些实验,这似乎发生在每个包的名字包含一个点(如bda.basenruamel.yaml),而且只对那些。在

我的问题:为什么?怎么解决这个问题呢?在

完整的可运行代码(这将更新您的系统范围的包!)位于https://gist.github.com/marnix/2f4efc1154547103bcec3783e6015bfc。在


Tags: path代码importoslibpackagesusrlocal
1条回答
网友
1楼 · 发布于 2024-05-16 05:49:13

bda是一个namespace package,因此不包括bda/__init__.py,因此在Python2中无法导入该包,除非重新启动解释器或手动调用site.main()。这是因为在您的.pth中创建了一个.pth文件,它告诉Python这是一个其他模块所在的命名空间。所有的.pth文件都是在解释器启动时由site.main()加载的,但由于您的文件是在解释器启动后创建的,Python对此一无所知。在

In [1]: import pip

In [2]: pip.main(['install', 'bda.basen'])
Collecting bda.basen
Requirement already satisfied: setuptools in /usr/local/lib/python2.7/site-packages (from bda.basen)
Installing collected packages: bda.basen
Successfully installed bda.basen-1.1
Out[2]: 0

In [3]: import bda.basen
                                     -
ImportError                               Traceback (most recent call last)
<ipython-input-3-e9d84961fc34> in <module>()
  > 1 import bda.basen

ImportError: No module named bda.basen

In [4]: import site

In [5]: site.main()

In [6]: import bda.basen

In [7]:

Python3.3+的行为与您预期的一样,因为它本机支持名称空间包,并且不需要您调用site.main()。在

相关问题 更多 >