Skip to content

Python Virtual Environments

Python virtual environments allow you to create isolated Python installations for different projects, preventing dependency conflicts between projects.

Creating Virtual Environments

Basic Setup

# Create virtual environment
python -m venv myenv

# Or with Python 3 explicitly
python3 -m venv myenv

# Create in current directory
python -m venv .

# Create with specific Python version
python3.11 -m venv myenv

Directory Structure

myproject/
├── venv/
│   ├── bin/              (Scripts on Linux/macOS)
│   ├── Scripts/          (Scripts on Windows)
│   ├── lib/              (Python packages)
│   ├── include/          (Headers)
│   └── pyvenv.cfg        (Configuration)
├── src/
├── requirements.txt
└── README.md

Activating Virtual Environments

Linux/macOS

# Activate
source venv/bin/activate

# Deactivate
deactivate

# Check activation
which python
python --version

Windows

# Activate (Command Prompt)
venv\Scripts\activate.bat

# Activate (PowerShell)
venv\Scripts\Activate.ps1

# Deactivate
deactivate

Verify Activation

# Should show venv path
which python

# Check Python version
python --version

# List installed packages
pip list

Managing Packages

Install Packages

# Install single package
pip install requests

# Install multiple packages
pip install requests flask sqlalchemy

# Install specific version
pip install requests==2.31.0

# Install with range
pip install requests>=2.28.0,<3.0

Freeze Dependencies

# Create requirements file
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

# Upgrade all packages
pip install -r requirements.txt --upgrade

# Show what would be installed
pip install --dry-run -r requirements.txt

requirements.txt Format

flask==3.0.0
sqlalchemy==2.0.23
requests>=2.28.0,<3.0
python-dotenv==1.0.0
pytest==7.4.0

Common Workflows

New Project Setup

# Create project directory
mkdir myproject
cd myproject

# Create virtual environment
python3 -m venv venv

# Activate
source venv/bin/activate

# Upgrade pip
pip install --upgrade pip

# Create requirements.txt
touch requirements.txt

# Create source directory
mkdir src

# Done!
# (venv) $ pip install -r requirements.txt

Adding Dependencies

# Activate venv
source venv/bin/activate

# Install package
pip install requests

# Update requirements
pip freeze > requirements.txt

# Git commit
git add requirements.txt
git commit -m "Add requests dependency"

Sharing Project

# Create requirements file
pip freeze > requirements.txt

# .gitignore (don't commit venv)
echo "venv/" >> .gitignore

# Commit requirements
git add requirements.txt
git commit -m "Add requirements"

# Share project...
# Recipient recreates:
# git clone <repo>
# python3 -m venv venv
# source venv/bin/activate
# pip install -r requirements.txt

Advanced Usage

Multiple Python Versions

# List available Python versions
ls /usr/bin/python*

# Create with Python 3.10
python3.10 -m venv py310_env

# Create with Python 3.11
python3.11 -m venv py311_env

# Switch between versions
source py310_env/bin/activate
deactivate
source py311_env/bin/activate

Environment Variables

# Create .env file
cat > .env <<EOF
DATABASE_URL=postgresql://user:pass@localhost/db
SECRET_KEY=secret123
DEBUG=True
EOF

# Load with python-dotenv
# In your Python code:
from dotenv import load_dotenv
load_dotenv()

Requirements Categories

# requirements.txt (core)
flask==3.0.0
sqlalchemy==2.0.23

# requirements-dev.txt
-r requirements.txt
pytest==7.4.0
black==23.7.0
flake8==6.0.0

# Install
pip install -r requirements-dev.txt

Troubleshooting

Virtual Environment Not Activating

# Check if venv exists
ls venv/

# Check script location
ls venv/bin/  # Linux/macOS
ls venv/Scripts/  # Windows

# Reinstall if needed
python3 -m venv --upgrade venv
source venv/bin/activate

Module Import Errors

# Verify correct venv is active
which python
python -c "import sys; print(sys.prefix)"

# Check installed packages
pip list

# Reinstall package
pip install --force-reinstall package_name

Pip Not Found

# Upgrade pip
python -m pip install --upgrade pip

# Or reinstall pip
python -m ensurepip --upgrade

Best Practices

  • Create virtual environment for each project
  • Always activate before installing packages
  • Commit requirements.txt, not venv folder
  • Use .gitignore to exclude venv
  • Document Python version needed
  • Use clear naming (venv, env, .venv)
  • Keep requirements.txt updated
  • Use separate requirements files for dev/prod

Integration with Tools

IDE Setup (VS Code)

{
  "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",
  "python.linting.enabled": true,
  "python.formatting.provider": "black"
}

Pre-commit Hooks

# Install pre-commit
pip install pre-commit

# Create .pre-commit-config.yaml
cat > .pre-commit-config.yaml <<EOF
repos:
  - repo: https://github.com/psf/black
    rev: 23.7.0
    hooks:
      - id: black
  - repo: https://github.com/PyCQA/flake8
    rev: 6.0.0
    hooks:
      - id: flake8
EOF

# Install hooks
pre-commit install

Docker Integration

Dockerfile

FROM python:3.11-slim

WORKDIR /app

# Copy requirements first
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application
COPY . .

# Run application
CMD ["python", "app.py"]

Resources


Last updated: 2025-07-06|Edit on GitHub