简体   繁体   English

Python导入可从一个文件夹进行,而不能从另一个文件夹进行

[英]Python importing works from one folder but not another

I have a project directory that is set up in the following way: 我有一个以以下方式设置的项目目录:

>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

In runTests.py I have the following import statements: runTests.py我具有以下导入语句:

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

The first two import statements work fine, but the second two give me the errors ImportError: No module named test1 and ImportError: No module named test2 . 前两个import语句工作正常,但是后两个给我以下错误ImportError: No module named test1ImportError: No module named test2 I can't see what is different between the tests and modules directories. 我看不到测试目录和模块目录之间的区别。

I'd be happy to provide more information as needed. 我很乐意根据需要提供更多信息。

When you run a script, Python adds the script's containing directory (here, scripts/ ) to sys.path . 运行脚本时,Python将脚本的包含目录(此处为scripts/ )添加到sys.path If your modules don't appear in sys.path any other way, that means Python may not be able to find them at all. 如果您的模块没有以其他任何方式出现在sys.path ,则意味着Python可能根本找不到它们。

The usual solution is to put your scripts somewhere in your module hierarchy and "run" them with python -m path.to.module . 通常的解决方案是将脚本放在模块层次结构中的某个位置,然后使用python -m path.to.module “运行”它们。 But in this case, you could just use an existing test runner: Python comes with python -m unittest discover , or you might appreciate something fancier like py.test ( pip install --user pytest ). 但是在这种情况下,您可以使用现有的测试运行程序:Python随附python -m unittest discover ,或者您可能会喜欢py.testpip install --user pytest )之类的东西。

The problem turned out to be that python didn't like the folder name tests. 问题原来是python不喜欢文件夹名称测试。 Changing the name to unit_tests solved the problem. 将名称更改为unit_tests解决了该问题。

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

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