简体   繁体   中英

ModuleNotFoundError: no module named src

This is the folder structure of my project in python (version 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:

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. In fact in test_main.py the following import fails:

from src.main import *

with the error: ModuleNotFoundError: No module named 'modules'

You said "When I run main.py..."

What you want is "When I run src/main.py"

$ python src/main.py

Take a look at $ python -m site output. Your PYTHONPATH env var should mention . dot, the current directory, and the site output should mention the top level directory of your project.

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

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