首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么Python ([‘`pip.main’,.])会给出ImportError,但只给带点的包名呢?

为什么Python ([‘`pip.main’,.])会给出ImportError,但只给带点的包名呢?
EN

Stack Overflow用户
提问于 2018-01-05 19:53:13
回答 1查看 390关注 0票数 0

当运行以下代码(Python2.7.12,在Linux上使用sudo -H)时,首先是包'plaitpy‘和'bda.basen’从未被安装的情况,

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-05 20:15:47

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

代码语言:javascript
复制
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]:

Python的行为与您预期的一样,因为它本机支持命名空间包,不需要您调用3.3+。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48120407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档