小编典典

ImportError:模块在那里时没有命名模块

python

我通常运行python2,但我正在使用python3。现在,我对为什么收到此错误感到困惑。

当我./test_web_events.pytests目录中运行命令时,我得到:

Traceback (most recent call last):
  File "./test_web_events.py", line 21, in <module>
    import qe.util.scratchstore as scratchstore
ImportError: No module named 'qe'

但是我的项目结构中有qe目录:

/python_lib
   Makefile
   /qe
      __init__.py
      /tests
         __init__.py
         test_web_events.py
      /util
         __init__.py
         scratchstore.py
      /trinity
         __init__.py

我尝试将/tests目录移入,/python_lib但是仍然出现相同的错误:

MTVL1289dd026:python_lib bli1$ ls
Makefile    qe      rundata     setup.sh    tests
MTVL1289dd026:python_lib bli1$ python3 tests/test_web_events.py 
Traceback (most recent call last):
  File "tests/test_web_events.py", line 21, in <module>
    import qe.util.scratchstore as scratchstore
ImportError: No module named 'qe'

这是我sys.path的python2

>>> import sys
>>> print sys.path
['', '/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']

sys.path 对于python3

>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages']

阅读 146

收藏
2021-01-20

共1个答案

小编典典

问题是这/python_lib不在Python路径中。Python 2和3的行为相同。

通常,请勿从Python包内部(内部)运行脚本,而应从顶级目录运行它们:

/python_lib$ python -m qe.tests.test_web_events

因此/python_lib是在Python路径中,/python_lib/qe/tests并非如此。假设有tests/__init__.py文件。

不要sys.path手动修改。这可能会导致与导入模块有关的细微错误。还有更好的选择,例如,如果您不想从运行脚本/python_lib,只需安装开发版本:

(your_virtualenv)/python_lib$ pip install -e .
2021-01-20