ModuleNotFoundError: No module named 'pytest'
Fixes ModuleNotFoundError: No module named 'pytest' by installing pytest into the exact Python interpreter running the code. Use when pytest is not found at all. Not for plugin load failures or version-conflict import errors.
TL;DR
Run python -m pip install pytest, then verify with pytest --version. This error means pytest is not installed in the Python environment that is actually running your code, which is usually a different interpreter or virtualenv than the one you installed into.
ModuleNotFoundError: No module named 'pytest'Fix it
- Confirm which Python is running. Run
which python(orwhere pythonon Windows) andpython --version. Then runpython -m pip show pytest. If pip says it is not installed, that is your answer.
- Expected:
pip show pytestprints version info, orWARNING: Package(s) not found: pytest.
- Install pytest into that exact interpreter. Run
python -m pip install pytest.
- Expected:
Successfully installed pytest-...plus its dependencies.
- Verify. Run
pytest --version.
- Expected: something like
pytest 8.3.4.
When this applies
- You just created a fresh virtualenv or container and forgot to install test deps.
- Your IDE runs a different interpreter than your terminal.
- CI installs dependencies in one step but runs pytest in another without them.
When it does not apply
- If
pytest --versionworks but a plugin fails to load, the problem is the plugin, not pytest itself. - If the error names a different module (like
_pytest.scope), see the version-conflict skills instead.
Tool compatibility
pytest 7.x and 8.x, Python 3.8+. Install via pip: pip install pytest.
Why it happens
Python resolves imports against sys.path of the running interpreter. pip install pytest may have targeted a different interpreter (system python vs venv vs conda), so the running one never sees it. Using python -m pip guarantees the installer and the runner are the same binary.
Edge cases
- On Debian/Ubuntu,
pip install pytestmay refuse and tell you to use a venv (PEP 668). Create one:python3 -m venv .venv && source .venv/bin/activate. - If you use conda, prefer
conda install pytestinside the active env, orpython -m pip install pytestwith the env's python.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.