Quick guide to requirements.txt files in Python

1. Purpose

  • Lists all package dependencies for a Python project
  • Allows easy installation of required packages using pip
  • Ensures consistent environments across different setups

2. Basic Usage

# Generate from currently installed packages (best used in virtualenv)
pip freeze > requirements.txt

# Install packages from file
pip install -r requirements.txt

3. File Format

# Exact version
Django==4.2.3

# Version range
requests>=2.25.1,<3.0

# Git repository
git+https://github.com/user/repo.git@branch#egg=package_name

# Local package
./path/to/local/package

# Environment markers (Python version specific)
pywin32 >=1.0; sys_platform == 'win32'

4. Advanced Features

  • Hashes (for secure installations):

    cryptography==3.4.7 \
      --hash=sha256:123...abc \
      --hash=sha256:456...def
    
  • Editable installs (for development):

    -e .
    

5. Best Practices

  1. Always use in combination with virtual environments
  2. Pin exact versions for production (==)
  3. Use ranges (>=, <=) carefully in development
  4. Separate dev vs prod requirements if needed
  5. Update regularly with pip freeze > requirements.txt

6. Common Commands

# Check installed packages
pip list

# Check outdated packages
pip list --outdated

# Install specific version
pip install package==1.2.3

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

7. Example Workflow

  1. Create virtual environment

    python -m venv venv
    source venv/bin/activate  # Linux/Mac
    venv\Scripts\activate  # Windows
    
  2. Install packages

    pip install django pandas
    
  3. Freeze requirements

    pip freeze > requirements.txt
    
  4. Share project with requirements.txt

Remember: For complex projects, consider using more advanced tools like pipenv or poetry, but requirements.txt remains the most widely supported method.