Python 在一个文件夹中导入正常,但在另一个文件夹中不行

0 投票
2 回答
2208 浏览
提问于 2025-04-18 08:38

我有一个项目文件夹,结构是这样的:

>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 test1ImportError: No module named test2。我看不出测试文件夹和模块文件夹有什么不同。

如果需要,我可以提供更多信息。

2 个回答

0

当你运行一个脚本时,Python 会把这个脚本所在的文件夹(这里是 scripts/)添加到 sys.path 里。如果你的模块没有以其他方式出现在 sys.path 中,那就意味着 Python 可能根本找不到它们。

通常的解决办法是把你的脚本放在模块的某个层级里,然后用 python -m path.to.module 来“运行”它们。不过在这种情况下,你可以直接使用一个现成的测试运行器:Python 自带了 python -m unittest discover,或者你可能会喜欢一些更高级的工具,比如 py.test(可以用 pip install --user pytest 来安装)。

1

问题的根源在于,Python 对文件夹名称 "tests" 不太喜欢。把这个文件夹改成 "unit_tests" 后,问题就解决了。

撰写回答