Fix: Python ModuleNotFoundError — Virtual Environments and Imports
Problem
Your Python script imports a package you installed, but Python can’t find it:
ModuleNotFoundError: No module named 'requests'
You’re certain you ran pip install requests. What’s going on?
Symptoms
pip listshows the package installed, but the script fails- The error occurs in VS Code or PyCharm but not in the terminal
- It works in one terminal window but not in another
pip installsays “Requirement already satisfied” but imports still fail- System Python vs. project Python version mismatch
Root Cause
Python looks for modules in specific directories defined by sys.path. The root cause is almost always a virtual environment mismatch:
- You installed the package globally but your IDE/terminal is using a virtual environment
- You installed in one venv but your script runs in another (or none)
- PYTHONPATH is set to wrong directories, causing imports to resolve incorrectly
- Package name vs import name differs (e.g.,
pip install beautifulsoup4→import bs4)
Solution
Step 1: Check which Python you’re using
which python
which python3
# Inside Python
import sys
print(sys.executable)
print(sys.path)
Step 2: Check if you’re in a virtual environment
echo $VIRTUAL_ENV
# If empty, no venv is active
# Activate your venv
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
Your terminal prompt should now show (venv) as a prefix.
Step 3: Verify the package is installed in the active environment
pip list | grep requests
# Or
python -m pip show requests
If not installed, install it:
pip install requests
Step 4: Create a fresh virtual environment
python -m venv venv
source venv/bin/activate
pip install requests
python your_script.py
Step 5: Fix IDE configuration
VS Code:
- Press
Cmd+Shift+P→ “Python: Select Interpreter” - Choose the interpreter inside your
venv/directory
PyCharm:
- Settings → Project → Python Interpreter
- Select or create a virtual environment
Step 6: Check package import name
Some packages have different install and import names:
| pip install | import |
|---|---|
beautifulsoup4 | bs4 |
scikit-learn | sklearn |
opencv-python | cv2 |
python-dotenv | dotenv |
Pillow | PIL |
Check the package documentation if unsure.
Verification
# Activate venv
source venv/bin/activate
# Verify Python path
which python
# /Users/you/project/venv/bin/python
# Test import
python -c "import requests; print(requests.__version__)"
Prevention
- Always use a virtual environment per project — never install globally
- Use
requirements.txtorpyproject.tomlto lock dependencies - Add
venv/to.gitignore - Use
pip freeze > requirements.txtafter installing packages - Select the correct interpreter in your IDE before starting work
- Use
python -m pipinstead of barepipto be explicit about which Python
References
Advertisement