How to Fix Python ModuleNotFoundError inside Virtualenv / Venv
The exception ModuleNotFoundError: No module named 'module_name' is one of the most frequent errors in Python development. It occurs when Python attempts to import a package that is missing from the search path (sys.path) of the active Python interpreter.
The exception ModuleNotFoundError: No module named 'module_name' is one of the most frequent errors in Python development. It occurs when Python attempts to import a package that is missing from the search path (sys.path) of the active Python interpreter.
Quick Diagnostics
ModuleNotFoundError: No module named 'package_name': Script is executed with global system Python or the package was installed outside the active virtual environmentsource venv/bin/activate), check binary path, and install package using python -m pip installStep-by-Step Solution
-
1
Step 1: Verify Virtual Environment Activation
Ensure your virtual environment is activated and check which Python binary is currently active:
BASH# On Linux / macOS: activate virtualenv source venv/bin/activate # On Windows (PowerShell): .\venv\Scripts\Activate.ps1 # Verify the active Python binary path which python # Linux/macOS where python # Windows(The path output should point to your project's
venv/bin/pythondirectory, not system/usr/bin/python). -
2
Step 2: Install Packages via Module Syntax
To guarantee that packages are installed into the virtual environment rather than system-wide Python, use
python -m pip:BASHpython -m pip install module_nameVerify that the module is installed in the active environment:
BASHpython -m pip list -
3
Step 3: Select the Correct Python Interpreter in Your IDE
If the script runs in the terminal but fails inside your code editor (e.g., VS Code or PyCharm):
- VS Code: Press
Ctrl + Shift + P(orCmd + Shift + Pon macOS), search forPython: Select Interpreter, and choose the interpreter insidevenv/bin/python. - PyCharm: Navigate to
Settings>Project>Python Interpreterand assign your project's virtual environment path.
- VS Code: Press
Prevention Advice
Recommended security practices:
- Use Dependency Files: Keep track of installed packages by maintaining a
requirements.txt(pip freeze > requirements.txt) or using modern tools like Poetry/uv. - Avoid Global
sudo pipInstalls: Never runsudo pip installfor project dependencies to avoid corrupting system Python modules. - Always Invoke
python -m pip: Callingpython -m pipprevents accidentally installing packages into a different Python executable when$PATHvariables are mismatched.