NNESTECHUB
← BACK TO JOURNAL

How to Fix ModuleNotFoundError in Python Virtual Environments

Find interpreter mismatches across terminals, VS Code, PyCharm, and Jupyter—and install packages into the environment that actually runs your code.

How to Fix ModuleNotFoundError in Python Virtual Environments

A successful pip install followed by ModuleNotFoundError almost always points to an interpreter mismatch: the package was installed into one Python environment while the script runs in another.


Why Python Cannot Find the Package

  1. A global interpreter and a virtual environment are being mixed.
  2. The virtual environment was not activated in the current terminal.
  3. The IDE selected a different interpreter from the terminal.
  4. A Jupyter notebook is attached to the wrong kernel.

Step 1: Identify the Active Interpreter

import sys

print("Executable:", sys.executable)
print("Search paths:")
for path in sys.path:
    print(" -", path)

The executable should point inside your project’s .venv or environment directory.


Step 2: Install Through the Intended Interpreter

Windows

.\.venv\Scripts\activate
python -m pip install package_name

Linux and macOS

source .venv/bin/activate
python3 -m pip install package_name

Using python -m pip ties the installer to the selected interpreter.


Step 3: Select the Correct VS Code Interpreter

  1. Open the project folder.
  2. Press Ctrl + Shift + P.
  3. Choose Python: Select Interpreter.
  4. Select the interpreter inside .venv, then open a fresh terminal.

Step 4: Register a Jupyter Kernel

python -m pip install ipykernel
python -m ipykernel install --user --name=my_project_env --display-name "Python (My Project)"

Switch the notebook to Python (My Project) from its kernel menu.

Quick Reference

SymptomCauseFix
Install succeeds, import failsWrong environmentUse python -m pip
Works in terminal, fails in IDEWrong IDE interpreterSelect .venv
Notebook import failsWrong kernelRegister ipykernel
Permission deniedGlobal protected directoryUse a virtual environment
JOIN THE CONVERSATION

What do you think?

0 COMMENTS

Be the first person to share a thought.

KEEP READINGExplore all stories →