Module Not Found Error: No module named 'src'

核能气质少年 提交于 2020-06-12 06:16:53

问题


Whenever I run main.py script in terminal error 'ModuleNotFoundError: No module named 'src' ' occurs. However it runs fine in PyCharm.

Project Structure:

-project
  -resources
  -src
    -package1
      -script1.py
      -script2.py
    -package2
      -script3.py
    -main.py

From terminal I run like this -

project$ python src/main.py

Error I am getting:

Traceback (most recent call last):
  File "src/main.py", line 1, in <module>
    from src.package1 import script1
ModuleNotFoundError: No module named 'src'

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']

回答1:


https://docs.python.org/3/tutorial/modules.html#the-module-search-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 variable sys.path. sys.path is initialized from these locations:

  • 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.

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.




回答2:


You can add a path to python runtime using sys.path:

import sys
sys.path.append('src/package1')
import script1


来源:https://stackoverflow.com/questions/57078689/module-not-found-error-no-module-named-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!