Python Virtual Environments and pip Cheat Sheet

In progress

Creating an isolated environment per project and managing its packages with pip. For new projects I now prefer uv, which does both.

Overview

Tool Role
venv standard-library module that creates a virtual environment
pip installs packages into the active environment
pyenv installs and switches between Python versions

Details

Create, Activate, Leave

python3.12 -m venv .venv               # create .venv in the project folder
source .venv/bin/activate              # macOS / Linux
.venv\Scripts\activate                 # Windows
which python                           # should point inside .venv
deactivate

With pyenv, create the environment from the selected version: pyenv exec python -m venv .venv.

pip

python -m pip install --upgrade pip
python -m pip install django
python -m pip show django              # installed version and location
python -m pip list
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt

References

Review cards

Flashcard Why keep direct dependencies in pyproject.toml rather than relying on pip freeze output?

pip freeze lists every installed package with its exact version, transitive ones included, so it no longer shows what the project actually needs.

Quiz Which command correctly activates a virtual environment in a Windows system?
  • source .venv/bin/activate
  • .venv\Scripts\activate
  • activate .venv
  • venv .venv

The activate script is called with the path to the virtual environment in Windows.