- Yair Mark
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:
foo/ -> some_module.py bar/ -> some_other_module.py
The command I ran was something like:
cd foo python some_module.py
I also tried
But received the same error. In this case,
some_module.py imports different things from
some_other_modules.py. 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!
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
__main__.py file for that folder.