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
- Always use in combination with virtual environments
- Pin exact versions for production (
==
) - Use ranges (
>=
,<=
) carefully in development - Separate dev vs prod requirements if needed
- 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
-
Create virtual environment
python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows
-
Install packages
pip install django pandas
-
Freeze requirements
pip freeze > requirements.txt
-
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.