Module Not Found Error when trying to run from cmd - jinwooklim/my-exp GitHub Wiki
참조 :
https://www.reddit.com/r/learnpython/comments/729u0t/module_not_found_error_when_trying_to_run_from_cmd/
https://stackoverflow.com/questions/22241420/execution-of-python-code-with-m-option-or-not
I have a project with this directory structure:
folder1
folder2
main.py
config.py
In main.py
, I have import config
. When I run it from inside PyCharm, it works fine, but when I run it from the command line with the following command (after cd-ing to folder1):
python folder2\main.py
I get this error:
Traceback (most recent call last):
File "folder2\main.py", line 4, in <module>
import config
ModuleNotFoundError: No module named 'config'
How do I fix this? I'm using Python 3.6 on Windows 7
Run python -m folder2.main
instead. The difference is what directory gets added to Python's path (the list of directories it looks in for modules to import). When you run python folder2/main.py
, it is folder2
that gets added to the path, meaning Python looks there for modules to import (in addition to all of the usual system directories). In contrast, when you run python -m folder2.main
, it is folder1
that gets added to the path.
In general, you should always use the python -m ...
form because it makes a lot of things import-related (especially relative imports) work more like you would expect them to.
If you want to see what's going on with the path, add this at the top of your main.py:
import sys
print(sys.path)