[英]ModuleNotFoundError: no module named src
This is the folder structure of my project in python (version 3.9.13):这是我在 python 中的项目的文件夹结构(版本 3.9.13):
src
modules
__init__.py
fileA.py
main.py
tests
__init__.py
test_main.py
test_fileA.py
When I run main.py I get the error "ModuleNotFoundError: no module named src" in line 4 (in main.py) which contains the following import:当我运行 main.py 时,我在第 4 行(在 main.py 中)收到错误“ModuleNotFoundError:没有名为 src 的模块”,其中包含以下导入:
from src.modules.fileA import classOfFileA
How can i resolve it?我该如何解决?
I tried to remove "src" from line 4 but this way I have some problems in tests.我试图从第 4 行删除“src”,但这样我在测试中遇到了一些问题。 In fact in test_main.py the following import fails:
事实上,在 test_main.py 中,以下导入失败:
from src.main import *
with the error: ModuleNotFoundError: No module named 'modules'出现错误:ModuleNotFoundError:没有名为“模块”的模块
You said "When I run main.py..."你说“当我运行 main.py 时......”
What you want is "When I run src/main.py"你想要的是“当我运行 src/main.py 时”
$ python src/main.py
Take a look at $ python -m site
output.查看
$ python -m site
输出。 Your PYTHONPATH env var should mention .
您的 PYTHONPATH env var 应该提到
.
dot, the current directory, and the site
output should mention the top level directory of your project.点、当前目录和
site
输出应提及项目的顶级目录。
Invoke your code from the project's top level, and the .
从项目的顶层调用您的代码,
.
dot in the env var will do the rest for you.环境变量中的点将为您完成剩下的工作。
Similarly,相似地,
$ python -m unittest tests/test_*.py
should work fine.应该工作正常。
(Or perhaps you prefer -m unittest test/test_main.py
, which is same as -m unittest test.test_main
.) (或者您可能更喜欢
-m unittest test/test_main.py
,它与-m unittest test.test_main
相同。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.