How do you automatically generate a requirements.txt file for a Python project? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

How do you automatically generate a requirements.txt file for a Python project?

message-square
0

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 freeze inside a virtual environment: If you run pip freeze against your global Python installation, it will dump dozens of unrelated system-wide packages into your project’s requirements.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-party pipreqs tool, which parses your project’s import statements:
    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 freeze outputs local file paths (-e file:///...) that break on other machines. Pass --exclude-editable to omit them:
    pip freeze --exclude-editable > requirements.txt
    
  • Separating direct dependencies from locked pins (pip-tools): For production workflows, maintain a clean requirements.in file listing only your top-level packages (e.g., requests, pandas) and compile a deterministic, hash-checked requirements.txt using pip-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.