【问题标题】:Python importing works from one folder but not anotherPython 导入工作从一个文件夹但不是另一个
【发布时间】:2014-06-04 21:50:10
【问题描述】:

我有一个按以下方式设置的项目目录:

>root
   > modules
       __init__.py
       module1.py
       > moduleClass
           __init__.py
           moduleClass1.py
           moduleClass2.py
   > scripts
       runTests.py
   > tests
       __init__.py
       test1.py
       test2.py
   run.sh

在runTests.py 我有以下导入语句:

import modules.module1
import modules.moduleClass.moduleClass2
import tests.test1
import tests.test2

前两个导入语句工作正常,但后两个给我错误ImportError: No module named test1 和ImportError: No module named test2。我看不出测试和模块目录之间有什么不同。

我很乐意根据需要提供更多信息。

【问题讨论】:

  • 运行 runTests.py 时你的工作目录是什么?
  • 那个目录下__init__.py的内容是什么?
  • 尝试重现,我在第一次导入时出错
  • @JohannesKeinestam 我从 root 运行 runTests.py。
  • @BartoszKP 所有__init__.py 文件都是空的,尽管我确实尝试使用路径添加语句。

标签: python python-import


【解决方案1】:

当您运行脚本时,Python 会将脚本的包含目录(此处为 scripts/)添加到 sys.path。如果您的模块没有以任何其他方式出现在 sys.path 中,则意味着 Python 可能根本无法找到它们。

通常的解决方案是将脚本放在模块层次结构中的某个位置,并使用python -m path.to.module“运行”它们。但在这种情况下,您可以只使用现有的测试运行器:Python 带有 python -m unittest discover,或者您可能会喜欢像 py.test (pip install --user pytest) 这样更高级的东西。

【讨论】:

    【解决方案2】:

    问题原来是 python 不喜欢文件夹名称测试。将名称更改为 unit_tests 解决了问题。

    【讨论】:

    • 真的吗?我在自己的项目中有一个目录“测试”,它工作正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2018-10-30
    • 2011-01-27
    • 2020-01-24
    相关资源
    最近更新 更多