Search code examples
pythondirectory-structure

Python ModuleNotFoundError when not in working directory; getcwd finds module


When I try to run a python file with python3.6 src/main.py (the working directory is one above src) there's this error when importing another module from path src:

from src import another_module

ModuleNotFoundError: No module named 'src'

When I do

print(os.getcwd())
print(os.listdir(os.getcwd()))

I get what's expected:

path/to/working/directory

['src']

The import works when I run the script with PyCharm, but I need to run it outside PyCharm.


Solution

  • Solved by creating another file run.py in the working directory that calls src/main.py and running run.py from the command line instead of src/main.py.