【问题标题】:'no module' error with __init__.py in directory using Nosetests使用 Nosetests 的目录中的 __init__.py 出现“无模块”错误
【发布时间】:2015-12-09 07:57:05
【问题描述】:

我的目录结构如下:

Chippa/

      bin/
         __init__.py
         app.py

      tests/
         __init__.py
         app_tests.py
         tools.py

      templates/
         hello_form.html
         index.html
         layout.html

      docs/

在我的app_tests.py 文件中,我有:

from nose.tools import *
from bin.app import app
from tests.tools import assert_response

当我尝试从tests 目录外部运行app_tests.py 时,在Chippa 目录内的测试目录之上一层,如下所示:

python tests/app_tests.py

我收到以下错误:

Traceback (most recent call last):
  File "tests/app_tests.py", line 3, in <module>
    from bin.app import app
ImportError: No module named bin.app

但我在bin 目录中确实有一个空的__init__.py,我认为这可以防止这个问题。我在这里想念什么?

【问题讨论】:

    标签: python python-2.7 import python-module


    【解决方案1】:

    要使导入工作,您必须首先实际运行适当的模块。所以,而不是

    python tests/app_tests.py
    

    ,试试

    python -m tests.app_tests
    

    【讨论】:

    • 试过python -m test.app_tests 得到:python -m test.app_tests /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: No module named test.app_tests
    • @SeanJarp:呃,tests.app_tests,对不起。
    • @minitech 你能解释一下这两个命令有什么区别吗?我经常遇到导入错误,要么通过“-m”解决,要么使用from __future__ import absolute_import(最常见的是使用scrapy——网络爬虫框架)。如果您建议我阅读有关导入的工作原理或任何可以让我避免此类错误的内容,那就太好了。
    猜你喜欢
    • 2021-09-13
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多