[英]Python importing works from one folder but not another
我有一个以以下方式设置的项目目录:
>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
前两个import语句工作正常,但是后两个给我以下错误ImportError: No module named test1
和ImportError: No module named test2
。 我看不到测试目录和模块目录之间的区别。
我很乐意根据需要提供更多信息。
运行脚本时,Python将脚本的包含目录(此处为scripts/
)添加到sys.path
。 如果您的模块没有以其他任何方式出现在sys.path
,则意味着Python可能根本找不到它们。
通常的解决方案是将脚本放在模块层次结构中的某个位置,然后使用python -m path.to.module
“运行”它们。 但是在这种情况下,您可以使用现有的测试运行程序:Python随附python -m unittest discover
,或者您可能会喜欢py.test ( pip install --user pytest
)之类的东西。
问题原来是python不喜欢文件夹名称测试。 将名称更改为unit_tests解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.