简体   繁体   English

运行nosetests时获取ImportError

[英]Getting ImportError when running nosetests

my_project
    -my_project
        - __init__.py
        - main.py
        - constants.py
        -test
            - __init__.py
            - test_main.py

test_main.py from my_project import main from my_project import main test_main.py

main.py import constants main.py import constants

When I run nosetests in my_project, I end up getting ImportError: No module named 'constants' 当我在my_project中运行nosetests时,我最终得到了ImportError: No module named 'constants'

Both __init__.py files are blank. 两个__init__.py文件都是空白的。

If I change import constants to from my_project import constants in main.py , nosetests work. 如果我将import constants更改为main.py from my_project import constants ,则nosetests可以正常工作。 However, now if I just run python main.py I get ImportError: No module named 'my_project' . 但是,现在如果我只运行python main.py我会得到ImportError: No module named 'my_project'

Can someone help me point out what I'm doing wrong? 有人能帮助我指出我做错了什么吗? I've searched quite a few posts but I haven't been able to fix it myself. 我搜索过很多帖子,但我自己无法解决这个问题。 Thanks. 谢谢。

In main.py -> import constants is an implicit relative import (bad). 在main.py中 - > import constants是一个隐式的相对导入(坏)。 It should be changed to the more usual from my_project import constants . 它应该from my_project import constants更改为更常见的。

You mentioned this makes nosetests work. 你提到这使得nosetests工作。 Note: you don't need the __init__.py in the tests sub-directory, and in fact this is usually discouraged. 注意:在test子目录中不需要__init__.py ,实际上通常不鼓励这样做。

Now to fix your error with python main.py having an import error, well that is normal if you haven't included it in your sys.path . 现在用python main.py修复你的错误导致导入错误,如果你没有将它包含在你的sys.path那么这是正常的。 There are various ways around this - 有各种各样的方法 -

  • execute from the project root directory (ie the uppermost my_project one) 从项目根目录执行(即最上面的my_project一个)
  • set the PYTHONPATH environment variable 设置PYTHONPATH环境变量
  • properly package and install your app using setuptools / easy_install etc 使用setuptools / easy_install等正确打包并安装您的应用程序

You're attempting a relative import in Python 2 style in a Python 3 project: import constants will, in Python 3, attempt to import constants at the main sys.path level. 您正在Python 3项目中尝试以Python 2样式进行相对导入:在Python 3中, import constants将尝试在主sys.path级别导入constants

Instead, use something like 相反,使用类似的东西

from . import constants

in main.py 在main.py中

See for example PEP 404 : 参见例如PEP 404

In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported. 在Python 3中,包中的隐式相对导入不再可用 - 仅支持绝对导入和显式相对导入。

and this SO question . 这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM