Python Virtual Environments: A Complete Guide
Python virtual environments isolate project dependencies so you don’t end up with conflicting package versions.
Why Use Virtual Environments?
- Project A needs Django 4.2, Project B needs Django 5.0
- Without isolation, you can only have one version installed system-wide
- Virtual environments solve this by giving each project its own package directory
Creating a Virtual Environment
Python 3.3+ includes venv out of the box:
# Create the environment
python3 -m venv venv
# Activate it
source venv/bin/activate # Linux / macOS
venv\Scripts\activate # Windows (Command Prompt)
# .\venv\Scripts\Activate.ps1 # Windows (PowerShell)Once activated, your prompt shows (venv):
(venv) ~/project $Installing Packages
# Inside the activated environment
pip install requests
pip install django==4.2
pip install "fastapi>=0.100,<1.0"
# Install from requirements file
pip install -r requirements.txtFreezing Dependencies
pip freeze > requirements.txtThis saves all installed packages and versions. Share this file so others can replicate your environment.
Deactivating
deactivateRequirements File Format
# requirements.txt
django==4.2.16
requests==2.31.0
pytest>=7.0,<8.0
fastapi>=0.100.0Common categories:
# requirements-dev.txt (development only)
pytest==7.4.0
black==23.9.0
ruff==0.1.0Common Workflow
# Start a new project
mkdir myproject && cd myproject
python3 -m venv venv
source venv/bin/activate
# Install deps as you go
pip install flask
pip freeze > requirements.txt
# Later, another developer sets up
git clone repo && cd repo
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txtVirtual Environment Location
By convention, the environment is named venv or .venv and placed in the project root. Add it to .gitignore:
# .gitignore
venv/
.env
__pycache__/
*.pycAlternatives to venv
| Tool | Description |
|---|---|
venv | Built-in, lightweight, standard |
virtualenv | Older, more features (works with Python 2) |
pipenv | Combines pip + venv + Pipfile |
poetry | Modern dependency management + packaging |
conda | Data science focused, handles non-Python deps |
Common Issues
“command not found: pip”
python3 -m pip install requestsPip is outdated
pip install --upgrade pipActivate in a script
#!/bin/bash
source venv/bin/activate
python script.pyOr better, use the venv’s Python directly:
#!/bin/bash
venv/bin/python script.pyRelated: Check our pip command fix guide for pip troubleshooting.