从github安装Python包到虚拟环境可以工作,但导入失败

时间:2018-02-25 18:00:57

标签: python python-3.x pip virtualenv python-packaging

  1. 我创建了一个名为PythonApplication
  2. 的python项目
  3. 我创建了一个虚拟环境env(Python 3.6(64位))
  4. 我在虚拟环境目录
  5. 中运行以下命令

    pip install git+git://github.com/BillMills/python-package-example.git
    

    我得到: enter image description here

    查看

    的目录结构
    ..\PythonApplication\PythonApplication\env\Lib\site-packages\myPackage
    

    我明白了 enter image description here

    enter image description here

    1. 然后我在PythonApplication.py
    2. 中添加以下代码

      import myPackage
      
      foo = 6
      bar = 7
      

      当我运行时,我收到以下错误:

        

      ModuleNotFoundError:没有名为' somePython'

      的模块

      我错过了什么?

      根据Saurav的评论,我重新做了一些步骤。但是,在创建环境后,我确实在命令提示符下激活了它,并在激活的环境中运行pip命令而不是命令提示符。结果没有改变。

      其他人评论说github.com/BillMills/python-package-example.git是用Python 2编写的,不适用于Python 3.如果这是正确的,需要更改什么?

      enter image description here

1 个答案:

答案 0 :(得分:2)

您在https://github.com/BillMills/python-package-example中使用的软件包使用的是Python 3不支持的导入样式。您可以在python-package-example/__init__.py中看到

import somePython

用于导入子模块,但python 3将假定somePython作为顶级模块存在。有关更好的解释,请参阅PEP-328

可以在https://github.com/kennethreitz/samplemod找到兼容Python 3的示例包。请注意,在sample/__init__.py子模块中使用相对导入导入(由前导'。'表示):

from .core import hmm 

如果你想修改python-package-example兼容,你需要改变它的__init__.py来使用绝对导入:

import myPackage.somePython as somePython

或相对导入:

from . import somePython