PYTHON VIRTUAL ENVIRONMENTS - SETUP & TROUBLESHOOTING
WHY USE VIRTUAL ENVIRONMENTS:
- Isolate project dependencies (each project gets its own packages)
- Avoid version conflicts between projects
- Keep system Python clean
- Make projects portable and reproducible
- Prevent "dependency hell"
SETUP STEPS:
-
Create virtual environment:
python -m venv project_env -
Activate virtual environment:
# Linux/Mac:
source project_env/bin/activate
# Windows:
project_env\Scripts\activate -
Install project packages:
pip install package1 package2 package3 -
Save dependencies (optional but recommended):
pip freeze > requirements.txt -
Run your script:
python your_script.py -
Deactivate when done:
deactivate
REQUIREMENTS.TXT - DEPENDENCY MANAGEMENT:
What is requirements.txt?
- Text file listing all packages and their versions
- Makes projects reproducible across different machines
- Standard way to share Python project dependencies
Creating requirements.txt:
After installing packages in your venv:
pip freeze > requirements.txt
Or create manually (example content):
PyMuPDF==1.23.5
requests==2.31.0
pandas>=1.5.0
Installing from requirements.txt:
In a new venv or clean environment:
pip install -r requirements.txt
Updating requirements.txt:
After adding new packages:
pip freeze > requirements.txt
Or update specific package:
pip install --upgrade package_name
pip freeze > requirements.txt
Best practices:
- Always include requirements.txt in your project
- Pin versions for reproducibility (==1.2.3)
- Use >= for flexible versions when needed
- Commit requirements.txt to version control
REPRODUCING ENVIRONMENT ON ANOTHER MACHINE:
- Create and activate venv (steps 1-2 above)
- Install from requirements:
pip install -r requirements.txt
TROUBLESHOOTING: Remove packages from global installation
If packages are installed globally and interfering with venv:
-
Make sure you're NOT in any venv:
deactivate -
Check what's installed globally:
pip list | findstr PackageName -
Uninstall globally:
pip uninstall PackageName -
Verify it's gone:
python -c "import PackageName"
(Should give "ModuleNotFoundError") -
Activate venv and install there:
project_env\Scripts\activate
pip install PackageName -
Test isolation:
# In venv - should work:
python -c "import PackageName; print('Works in venv')"
deactivate
# Outside venv - should fail:
python -c "import PackageName"
OPTIONAL ALIASES (if python3 command not found):
Linux/Mac (add to ~/.bashrc or ~/.bash_profile):
alias python=python3
alias pip=pip3
Windows (PowerShell profile):
Set-Alias python python3
Set-Alias pip pip3
pip install gotcha
Use python3 -m pip install package
instead of pip install package
- Ensures you're using the correct Python's pip
- Works when
pip
isn't in PATH - Avoids installing to wrong Python version when multiple versions exist
- More reliable and explicit