/errors/python/modulenotfounderror-no-module-named
ModuleNotFoundError: No module named '…'
- tool
- Python
- exit code
- 1
- versions
- Python 3.6+
- os
- any
Python raises ModuleNotFoundError: No module named 'x' when the interpreter running your code cannot find module x on its import path. Almost always the package is either not installed, or installed for a different interpreter or virtual environment.
Reproduce the error
python -c "import requests"Output · exit 1
Traceback (most recent call last):
File "<string>", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'The process exits with status 1 and the traceback names the missing module.
Check which interpreter runs your code
Install packages with the same interpreter that runs the code. python -m pip guarantees that, while a bare pip may belong to another Python on PATH.
python -c "import sys; print(sys.executable)"
python -m pip --versionBoth lines must point inside the same environment (the active virtual environment, or the system installation).
Check whether a module is importable without importing it
importlib.util.find_spec returns None when a module cannot be found, which is useful in scripts and health checks.
python -c "import importlib.util as u; print(u.find_spec('json') is not None, u.find_spec('requests') is not None)"Output
True False
Fix
- Install into the interpreter you run:
python -m pip install requests. - In a virtual environment, activate it first (
source .venv/bin/activateon Linux and macOS,.venv\Scripts\activateon Windows), or run.venv/bin/pythondirectly. - Use the import name, not the distribution name. Common mismatches:
| pip install | import |
|---|---|
| PyYAML | yaml |
| Pillow | PIL |
| scikit-learn | sklearn |
| beautifulsoup4 | bs4 |
| opencv-python | cv2 |
| python-dateutil | dateutil |
FAQ
What is the difference between ImportError and ModuleNotFoundError?
ModuleNotFoundError is a subclass of ImportError raised when the module itself cannot be located. ImportError alone usually means the module was found but a name inside it could not be imported.
Why does pip say the package is installed but Python cannot import it?
pip and python point to different interpreters. Run python -m pip install so the package lands in the environment of the interpreter you use.