Published on

Python Run Module from the Commandline and Dealing with the ModuleNotFoundError


One thing that I could not wrap my head around until recently is how to run the __main__ inside of a module from the command line in Python. I kept getting the error: ModuleNotFoundError: No module named 'foo'.

This same module ran without issues from Pycharm.

My project looks for example like below:


The command I ran was something like:

cd foo

I also tried

python foo/

But received the same error. In this case, imports different things from The error was related to this project import and not Pip dependencies from the virtual environment - those imported fine.

Today I revisited this issue and found this answer.

The solution is to use the -m flag and the package dot notation to get to the module. This approach puts the other modules onto the PYTHONPATH and Python can now see all project modules!

python foo/some_module

This will run as long as some_module has a main method defined as below:

if __name__ == "main":
    # run your code

Alternatively, you can also define the main functionality in a file for that folder.