Virtual environments are one of those things Python developers either learn early and love, or learn late and regret. If you have ever broken a system Python installation, had two projects silently conflict with each other, or inherited a project with no dependency file at all, you already know why they matter.
This guide covers everything: why virtual environments exist, how to create and use them on every platform, how to manage dependencies with pip and pyproject.toml, how to handle dev versus production dependencies, and what to do when things go wrong. Practical examples throughout.
Quick Reference: Common Commands
| Task | Command |
|---|---|
| Create a virtual environment | python -m venv .venv |
| Activate (Linux/macOS) | source .venv/bin/activate |
| Activate (Windows CMD) | .venv\Scripts\activate.bat |
| Activate (Windows PowerShell) | .venv\Scripts\Activate.ps1 |
| Deactivate | deactivate |
| Install a package | pip install requests |
| Install from requirements file | pip install -r requirements.txt |
| Save installed packages | pip freeze > requirements.txt |
| Show installed packages | pip list |
| Show package details | pip show requests |
| Upgrade pip itself | pip install --upgrade pip |
| Uninstall a package | pip uninstall requests |
| Install in editable mode | pip install -e . |
| Install with extras | pip install "fastapi[standard]" |
Why Virtual Environments Exist
Python installs packages globally by default. When you run pip install flask, it lands in your system Python's site-packages directory — the same place every other project's packages go. That seems fine until:
- Project A needs Flask 2.x, Project B needs Flask 3.x. They can't both win.
- You upgrade a package for one project and silently break another.
- A new team member installs your project and gets different package versions than you have.
- You run
pip installas root and corrupt your OS's Python (this is particularly bad on Linux).
A virtual environment is a self-contained directory with its own Python binary and its own site-packages. Each project gets its own isolated environment. You can run hundreds of projects on the same machine, each with completely independent dependencies, and they will never interfere with each other.
The name .venv (with a dot) is the modern convention — the dot hides the directory from directory listings by default and signals that it is a tool artifact, not source code.
Creating a Virtual Environment with python -m venv
Python 3.3+ ships with venv as part of the standard library. You do not need to install anything extra.
# Navigate to your project directory first
cd my-project
# Create a virtual environment named .venv
python -m venv .venv
On some Linux distributions, you may need to install the python3-venv package first:
# Ubuntu/Debian
sudo apt install python3-venv
# Then create the environment
python3 -m venv .venv
What gets created:
my-project/
└── .venv/
├── bin/ (Linux/macOS) or Scripts/ (Windows)
│ ├── python
│ ├── python3
│ └── pip
├── include/
└── lib/
└── python3.x/
└── site-packages/ ← your packages go here
The bin/python (or Scripts/python.exe) binary is a copy of or symlink to your system Python, pointing to this isolated site-packages. When you activate the environment, this binary takes priority over the system Python.
Specifying a Python Version
If you have multiple Python versions installed, you can specify which one to use:
# Use Python 3.11 specifically
python3.11 -m venv .venv
# Or using a full path
/usr/local/bin/python3.12 -m venv .venv
Useful venv Options
# Create with access to system packages (rarely needed, usually a bad idea)
python -m venv --system-site-packages .venv
# Create without pip (if you plan to install pip manually)
python -m venv --without-pip .venv
# Upgrade the environment's core components (useful after a Python upgrade)
python -m venv --upgrade .venv
Activating and Deactivating
Creating the environment does not automatically use it. You need to activate it, which modifies your shell's PATH so the environment's Python and pip take precedence.
Linux and macOS
source .venv/bin/activate
Your prompt will change to show the active environment:
(.venv) user@machine:~/my-project$
Windows (Command Prompt)
.venv\Scripts\activate.bat
Windows (PowerShell)
.venv\Scripts\Activate.ps1
If you get an error about execution policy, run this first:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Verifying the Activation Worked
# Should show the path inside your .venv
which python # Linux/macOS
where python # Windows
# Should show the venv's Python, not the system Python
python --version
pip --version
Deactivating
When you are done working on the project:
deactivate
Your prompt returns to normal and the system Python takes over again.
Running Without Activating
You can also call the venv's Python directly without activating, which is useful in scripts and CI:
# Linux/macOS
.venv/bin/python script.py
.venv/bin/pip install requests
# Windows
.venv\Scripts\python.exe script.py
.venv\Scripts\pip.exe install requests
This is the approach most CI/CD pipelines use — no shell activation needed, just call the binary directly.
Installing Packages with pip
With your virtual environment active, pip install installs packages into the environment, not the system.
Basic Installation
pip install requests
pip install flask
pip install "django>=4.2,<5.0" # version constraints
pip install "fastapi[standard]" # with extras
Installing Multiple Packages at Once
pip install requests flask sqlalchemy
Installing a Specific Version
pip install requests==2.31.0
pip install "requests>=2.28.0,<3.0.0"
Upgrading Packages
# Upgrade a specific package
pip install --upgrade requests
# Upgrade pip itself (do this regularly)
pip install --upgrade pip
Installing from a Git Repository
pip install git+https://github.com/psf/requests.git
pip install git+https://github.com/psf/requests.git@v2.31.0 # specific tag
Listing and Inspecting Packages
# List all installed packages
pip list
# List outdated packages
pip list --outdated
# Show details about a specific package
pip show requests
# Output:
# Name: requests
# Version: 2.31.0
# Location: /home/user/my-project/.venv/lib/python3.11/site-packages
# Requires: certifi, charset-normalizer, idna, urllib3
requirements.txt vs pyproject.toml
This is where most Python dependency guides get confusing. Here is the clear version.
requirements.txt: The Old Way (Still Valid)
requirements.txt is a plain text file listing packages and version pins. It is simple and universally understood.
Generating it:
pip freeze > requirements.txt
pip freeze outputs every installed package with its exact version:
certifi==2023.11.17
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.1.0
Notice it lists not just requests, but also requests' own dependencies (certifi, urllib3, etc.). This is a fully pinned lockfile — good for reproducibility, but it includes transitive dependencies you did not explicitly choose.
Installing from it:
pip install -r requirements.txt
The problem with pip freeze: It captures everything in your environment, including dev tools like pytest and black. You end up pinning test dependencies into your production install file.
A better approach: maintain requirements.txt manually with only your direct dependencies, and use pip freeze to generate a separate requirements.lock.txt for exact reproducibility.
# requirements.txt (manual, human-maintained)
requests>=2.28.0
flask>=3.0.0
sqlalchemy>=2.0.0
# requirements-dev.txt (dev-only tools)
pytest>=7.0.0
black>=23.0.0
ruff>=0.1.0
Install them separately:
pip install -r requirements.txt # production
pip install -r requirements.txt -r requirements-dev.txt # development
pyproject.toml: The Modern Way
pyproject.toml is the modern standard, defined by PEP 518 and PEP 621. It is a single file that defines your project metadata, dependencies, build configuration, and tool settings (black, ruff, pytest, mypy, etc.) all in one place.
A minimal pyproject.toml:
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.backends.legacy:build"
[project]
name = "my-project"
version = "1.0.0"
description = "My Python project"
requires-python = ">=3.11"
dependencies = [
"requests>=2.28.0",
"flask>=3.0.0",
"sqlalchemy>=2.0.0",
]
Installing from pyproject.toml:
pip install . # install the project and its dependencies
pip install -e . # editable install (changes to source are immediately reflected)
The -e flag is essential during development — you edit your code and the changes are immediately available without reinstalling.
Optional Dependencies (Dev vs Production in pyproject.toml)
pyproject.toml has a proper mechanism for optional dependency groups:
[project]
name = "my-project"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = [
"requests>=2.28.0",
"flask>=3.0.0",
"sqlalchemy>=2.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
"black>=23.0.0",
"ruff>=0.1.0",
"mypy>=1.0.0",
]
test = [
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
"httpx>=0.25.0", # for testing async clients
]
Install with extras:
pip install -e . # production only
pip install -e ".[dev]" # production + dev tools
pip install -e ".[dev,test]" # all groups
This is clean and explicit: the pyproject.toml is the source of truth, and you choose which groups to install in each context.
Managing Dev vs Production Dependencies
The goal is to keep production installs lean — only the packages your application actually needs to run. Dev dependencies (test runners, linters, type checkers, debuggers) have no place in production images.
Pattern 1: Separate requirements files
requirements.txt # direct production deps
requirements-dev.txt # dev/test tools (references requirements.txt)
requirements-ci.txt # CI-specific tools (references requirements.txt)
requirements-dev.txt:
-r requirements.txt
pytest>=7.0.0
pytest-cov>=4.0.0
black>=23.0.0
ruff>=0.1.0
mypy>=1.0.0
ipdb>=0.13.0
Pattern 2: pyproject.toml with optional groups (recommended for new projects)
As shown above, optional dependency groups in pyproject.toml are the cleanest modern approach. One file, explicit groups, and pip handles the rest.
Pattern 3: pip-tools for lockfiles
pip-tools generates fully pinned lockfiles from your unpinned pyproject.toml or requirements.in files:
pip install pip-tools
# Compile production lockfile
pip-compile pyproject.toml --output-file requirements.lock
# Compile dev lockfile
pip-compile --extra dev pyproject.toml --output-file requirements-dev.lock
# Install from lockfile
pip-sync requirements.lock # production
pip-sync requirements-dev.lock # development
pip-sync is particularly useful — it installs exactly what is in the lockfile and removes anything that should not be there, keeping your environment clean.
In Docker: Never Install Dev Dependencies in Production Images
# Production stage
FROM python:3.11-slim as production
WORKDIR /app
COPY pyproject.toml .
RUN pip install --no-cache-dir .
# Development stage (extends production)
FROM production as development
RUN pip install --no-cache-dir ".[dev]"
COPY . .
Common Errors and Troubleshooting
"pip: command not found" after creating a venv
You likely forgot to activate the environment, or activation failed silently.
# Check if the venv exists
ls .venv/bin/
# Activate explicitly
source .venv/bin/activate
# Or call pip directly
.venv/bin/pip install requests
"ModuleNotFoundError" even though you pip installed it
Almost always means the package was installed into a different Python than the one you are running. Check:
# Which Python are you running?
which python
python -c "import sys; print(sys.executable)"
# Which Python does your venv use?
.venv/bin/python -c "import sys; print(sys.executable)"
If they differ, you are running outside the venv. Activate it or use .venv/bin/python script.py directly.
"ERROR: Could not find a version that satisfies the requirement"
# Check you have the right package name (use PyPI search)
pip install requests # not "python-requests" or "request"
# Check your Python version is compatible
python --version
pip install "package>=X.Y" # check package's requires-python
# Try upgrading pip — older pip may not resolve new packages
pip install --upgrade pip
SSL Certificate Errors
# Temporary workaround (not for production)
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org requests
# Permanent fix: update certificates
pip install --upgrade certifi
"Permission denied" when installing
You are trying to install into the system Python. Either activate your venv or use the --user flag:
pip install --user requests # installs to ~/.local (avoid if using venvs)
Better: just activate your virtual environment first.
Conflicting Dependencies
# See the full dependency tree
pip install pipdeptree
pipdeptree
# Check what requires a specific package
pipdeptree --reverse --packages requests
If two packages require incompatible versions of the same dependency, you may need to find compatible version ranges or use separate virtual environments for each project.
"The virtual environment was not created successfully" on Ubuntu/Debian
sudo apt install python3-venv python3-full
python3 -m venv .venv
Best Practices for Projects
1. Always use a virtual environment — no exceptions
Even for tiny scripts. The habit costs nothing and saves hours of debugging version conflicts.
2. Name it .venv and gitignore it
# .gitignore
.venv/
venv/
env/
__pycache__/
*.pyc
Never commit the virtual environment directory. It contains platform-specific binaries and absolute paths that will not work on another machine.
3. Commit your dependency file, not the venv
Your requirements.txt or pyproject.toml goes in version control. Your .venv does not.
# Other developers set up their own environment like this:
git clone https://github.com/you/my-project
cd my-project
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
4. Pin versions for applications, use ranges for libraries
- Applications (web apps, scripts, tools): pin exact versions (
requests==2.31.0) for reproducibility - Libraries (packages others install): use version ranges (
requests>=2.28.0,<3.0.0) to avoid conflicts with your users' environments
5. Upgrade pip after creating a new venv
python -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
Older pip versions have resolver bugs and may install incompatible packages.
6. Use pyproject.toml for new projects
It is the current standard. It is better structured than requirements.txt, handles optional dependencies cleanly, and integrates with modern build tools. Tools like ruff, black, mypy, and pytest all read their config from pyproject.toml, so you get one file instead of five.
7. Keep a Makefile or scripts for common setup
.PHONY: install install-dev test lint
install:
python -m venv .venv
.venv/bin/pip install --upgrade pip
.venv/bin/pip install -e .
install-dev:
python -m venv .venv
.venv/bin/pip install --upgrade pip
.venv/bin/pip install -e ".[dev]"
test:
.venv/bin/pytest
lint:
.venv/bin/ruff check .
.venv/bin/black --check .
New contributors run make install-dev and have a working environment in under a minute.
8. Use .python-version for version pinning
If your team uses pyenv, a .python-version file ensures everyone uses the same Python version:
echo "3.11.7" > .python-version
pyenv automatically switches to that version when you enter the directory.
9. Document the setup in your README
Always include a "Getting Started" section:
## Setup
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
pytest
Three commands. Anyone can follow that.
Putting It All Together: A Real Project Setup
Here is what a well-structured Python project looks like from scratch:
mkdir my-project && cd my-project
git init
python -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pyproject.toml:
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.backends.legacy:build"
[project]
name = "my-project"
version = "0.1.0"
description = "A well-structured Python project"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.25.0",
"pydantic>=2.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
"ruff>=0.1.0",
"black>=23.0.0",
"mypy>=1.0.0",
]
[tool.ruff]
line-length = 88
select = ["E", "F", "I"]
[tool.black]
line-length = 88
target-version = ["py311"]
[tool.mypy]
python_version = "3.11"
strict = true
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=src --cov-report=term-missing"
.gitignore:
.venv/
__pycache__/
*.pyc
*.egg-info/
dist/
build/
.coverage
htmlcov/
Install everything:
pip install -e ".[dev]"
One command, one file, fully isolated environment, all tools configured. That is the target state for any Python project.
Go Further
Virtual environments are just the foundation. Once your environment is solid, the next step is a project structure that scales — organized source layout, a proper test suite, CI that runs your linter and tests on every push, and a deployment story that does not involve SSHing into a server and running git pull.
If you want to skip the trial-and-error and start with a production-ready structure:
- Python Project Template ($19) — A complete starter project with
pyproject.toml,src/layout, pytest configuration, ruff and black setup, GitHub Actions CI workflow, Docker support, and a Makefile with all the common commands. Clone it, rename it, start building. Everything in this guide is already set up for you. - Python Developer Bundle ($49) — The full toolkit: the project template plus cheat sheets for Python, pip, virtual environments, pyproject.toml configuration, pytest patterns, and type annotations. Reference material you will actually use day-to-day, not a 400-page book. Covers everything from environment setup to async patterns to packaging and publishing to PyPI.