Search code examples
pythonpycharm

ModuleNotFoundError: Python files seem to behave differentely inside and outside of Pycharm


Some months ago, I developed a project using PyCharm and it worked just fine. Now if I want to enter the venv venv\Scripts\activate and start the project from cmd python src\main.py, I receive ModuleNotFoundError No module named 'src' when main.py and other files try to import stuff from src.

When I move all my files from src to the project root folder, it straightens out. A lot has happened with this project and my Python environment, but that's frankly besides the point.

Why does main.py "see" the project from the root in PyCharm, but now in command line it doesn't? And how can I deal with it?


Solution

  • Given the project tree

    .
    └── src
        ├── lib.py
        └── main.py
    
    

    ... with main.py

    import src.lib
    

    When you run main.py in PyCharm it adds the project root to PYTHONPATH by default. Hence when Python tries to resolve import src.lib, it successfully finds package src in sys.path under the project root.

    When you run python src/main.py - the project root is not added to PYTHONPATH, only src/ itself (parent folder of the executed module). So Python cannot resolve import src as the src package is nowhere to be found under sys.path entries.

    I hope it makes sense.

    You can emulate PyCharm's behavior in the terminal with

    PYTHONPATH=. python src/main.py