简体   繁体   中英

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:

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 . 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 . If your modules don't appear in sys.path any other way, that means Python may not be able to find them at all.

The usual solution is to put your scripts somewhere in your module hierarchy and "run" them with 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 ).

The problem turned out to be that python didn't like the folder name tests. Changing the name to unit_tests solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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