Skip to content

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.txt

Freezing Dependencies

pip freeze > requirements.txt

This saves all installed packages and versions. Share this file so others can replicate your environment.

Deactivating

deactivate

Requirements File Format

# requirements.txt
django==4.2.16
requests==2.31.0
pytest>=7.0,<8.0
fastapi>=0.100.0

Common categories:

# requirements-dev.txt (development only)
pytest==7.4.0
black==23.9.0
ruff==0.1.0

Common 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.txt

Virtual 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__/
*.pyc

Alternatives to venv

ToolDescription
venvBuilt-in, lightweight, standard
virtualenvOlder, more features (works with Python 2)
pipenvCombines pip + venv + Pipfile
poetryModern dependency management + packaging
condaData science focused, handles non-Python deps

Common Issues

“command not found: pip”

python3 -m pip install requests

Pip is outdated

pip install --upgrade pip

Activate in a script

#!/bin/bash
source venv/bin/activate
python script.py

Or better, use the venv’s Python directly:

#!/bin/bash
venv/bin/python script.py

Related: Check our pip command fix guide for pip troubleshooting.