Run pip freeze > requirements.txt inside an activated virtual environment to capture all currently installed packages with exact pinned versions, or use pipreqs (pipreqs .) to scan your .py source files and generate a minimal requirements.txt containing only the packages your project actually imports.
Basic Example
# 1. Activate your project's virtual environment first (Linux/macOS)
source .venv/bin/activate
# (On Windows PowerShell: .venv\Scripts\Activate.ps1)
# 2. Export all installed packages and exact versions to requirements.txt
pip freeze > requirements.txt
Example requirements.txt output:
certifi==2026.1.4
charset-normalizer==3.4.1
idna==3.10
requests==2.32.3
urllib3==2.3.0
Key Details & Alternative Tools
- Always run
pip freezeinside a virtual environment: If you runpip freezeagainst your global Python installation, it will dump dozens of unrelated system-wide packages into your project’srequirements.txt. - Generating only imported packages (
pipreqs): When you forgot to use a virtual environment—or want only top-level dependencies rather than transitive sub-dependencies—use the third-partypipreqstool, which parses your project’simportstatements:pip install pipreqs pipreqs /path/to/project --force - Excluding editable local installs (
--exclude-editable): If you have local packages installed in editable mode (pip install -e .),pip freezeoutputs local file paths (-e file:///...) that break on other machines. Pass--exclude-editableto omit them:pip freeze --exclude-editable > requirements.txt - Separating direct dependencies from locked pins (
pip-tools): For production workflows, maintain a cleanrequirements.infile listing only your top-level packages (e.g.,requests,pandas) and compile a deterministic, hash-checkedrequirements.txtusingpip-compile:pip install pip-tools pip-compile requirements.in # Generates requirements.txt with full dependency tree
Comparison of requirements.txt Generation Methods
| Method / Tool | Command | Includes Sub-Dependencies? | Works Without a Clean Venv? | Best Used When |
|---|---|---|---|---|
pip freeze |
pip freeze > requirements.txt |
Yes (all installed packages) | No (captures global packages) | Reproducing an exact, isolated virtual environment snapshot. |
pipreqs |
pipreqs . --force |
No (only imported libraries) | Yes (scans .py imports) |
Cleaning up projects developed in a shared/global environment. |
pip-tools (pip-compile) |
pip-compile requirements.in |
Yes (compiled from .in) |
Yes | Production projects needing clean separation of direct vs. pinned dependencies. |
uv pip compile |
uv pip compile pyproject.toml -o requirements.txt |
Yes (ultra-fast lock resolution) | Yes | Modern projects using pyproject.toml and Astral’s uv toolchain. |
You must log in or register to comment.
