找不到模块错误:没有名为“ src”的模块 [英] Module Not Found Error: No module named 'src'
问题描述
每当我在终端错误 ModuleNotFoundError中运行main.py脚本时,都不会发生名为 src的模块。
Whenever I run main.py script in terminal error 'ModuleNotFoundError: No module named 'src' ' occurs. However it runs fine in PyCharm.
项目结构:
-project
-resources
-src
-package1
-script1.py
-script2.py
-package2
-script3.py
-main.py
从终端我这样运行-
project$ python src/main.py
我遇到的错误:
Traceback (most recent call last):
File "src/main.py", line 1, in <module>
from src.package1 import script1
ModuleNotFoundError: No module named 'src'
我已经尝试过将文件夹/软件包'src'的绝对路径添加到sys.path
I have already tried adding absolute path of folder/package 'src' to sys.path
main.py
from src.package1 import script1
from src.package1 import script2
from src.package2 import script3
if name=="__main__":
...
...
sys.path
current sys.path is ['/home/xyz/Projects/project/src', '/home/xyz/Apps/anaconda3/envs/project/lib/python37.zip', '/home/xyz/Apps/anaconda3/envs/project/lib/python3.7', '/home/xyz/Apps/anaconda3/envs/project/lib/python3.7/lib-dynload', '/home/xyz/Apps/anaconda3/envs/project/lib/python3.7/site-packages', 'src/main.py']
推荐答案
https://docs.python.org/3/tutorial/modules.html#the-module-search-path
导入名为垃圾邮件的模块时,解释程序首先搜索具有该名称的内置模块。如果找不到,它将在变量
sys.path $ c $给定的目录列表中搜索名为
spam.py
的文件。 c>。从以下位置初始化sys.path
:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named
spam.py
in a list of directories given by the variablesys.path
.sys.path
is initialized from these locations:
- 包含输入脚本的目录(或未指定文件时的当前目录)。
-
PYTHONPATH
(目录名列表,语法与shell变量PATH)。 - 与安装有关的默认值。
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variable PATH).- The installation-dependent default.
由于您提供了文件 src / main.py
,因此其包含的文件夹将成为搜索根目录。您可以在不指定 src。
部分的情况下导入模块。
Since you supply a file, src/main.py
, its containing folder is going to be the search root. You could import the modules without specifying the src.
part.
这篇关于找不到模块错误:没有名为“ src”的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!