简体   繁体   中英

ModuleNotFoundError in a Python project using packages

I have a Python project (python 3.6) with a rather simple package structure. My goal is to have a package containing modules which are reused across other packages. Here is the structure:

    my_project                   
    ├── /docs           
    ├── /src
    │   ├── __init__.py                
    │   ├── /common
    │   |    |── __init__.py      
    │   |    |── common_module.py
    │   ├── /packageA
    │   |    |── __init__.py      
    │   |    |── modA.py

The problem is that when I do the following inside modA.py :

    from src.common import common_module as cm

I get the following error: ModuleNotFoundError: No module named src.common

What I have tried so far is

  • making sure I have a correct package structure as in https://docs.python.org/3/tutorial/modules.html
  • extending the PYTHONPATH in the virtual environment I am using by export PYTHONPATH=<path_to_project>/src
  • placing an __init__.py inside /my_project as well
  • read other question on StackOverflow but none of them provided a solution. Some of them were doing hacky stuff with sys.path that was said to not a good solution even if it would work.

None of these worked and I have been struggling with this problem for a while now so any suggestion would be appreciated.

为了使此导入正常进行,PYTHONPATH必须为.../my_project ,而不是.../my_project/src

Yes you should put __init__.py in project ,
then export PYTHONPATH = <LOCAL_PATH_TO_...>/project

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