3.4 KiB
pip
pip is Python’s package manager.
It’s the tool you use to install, upgrade, and remove Python libraries that aren’t included in the standard library.
Think of it like:
apton Debian/Ubuntudnfon Fedoranpmfor JavaScript
What does pip do?
With pip, you can:
- Install packages
pip install requests
- Upgrade packages
pip install --upgrade requests
- Uninstall packages
pip uninstall requests
- List installed packages
pip list
- Install from a requirements file
pip install -r requirements.txt
Where do packages come from?
By default, pip downloads packages from PyPI (Python Package Index):
- https://pypi.org
- Contains hundreds of thousands of Python libraries
- Example packages:
requests,numpy,flask,django,pandas
pip vs Python itself
- Python → the programming language + standard library
- pip → installs extra libraries written by the community
Example:
import math # standard library (no pip needed)
import requests # external library (installed via pip)
pip and Python versions
On many systems:
pip→ Python 2 or system defaultpip3→ Python 3
Safer way (recommended):
python3 -m pip install requests
This ensures pip matches the Python version you’re using.
Virtual environments
pip works best with virtual environments (venv) to avoid breaking system Python:
python3 -m venv venv
source venv/bin/activate
pip install flask
What is requirements.txt?
requirements.txt is a list of Python packages (and versions) your project depends on.
Example:
flask==3.0.0
requests>=2.31.0
gunicorn
Install dependencies from requirements.txt
Basic usage
pip install -r requirements.txt
Safer (recommended)
python3 -m pip install -r requirements.txt
This ensures pip matches your Python version.
Use with a virtual environment (best practice)
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
After activation, all packages go into venv/.
Generate requirements.txt from current environment
If you already installed packages:
pip freeze > requirements.txt
⚠️ This captures everything installed in the environment.
Common version formats
flask==3.0.0 # exact version (reproducible builds)
requests>=2.31.0 # minimum version
numpy~=1.26.0 # compatible release
django<5.0 # version upper limit
Install from multiple requirement files
pip install -r base.txt -r dev.txt
Useful for:
base.txt→ productiondev.txt→ development tools (pytest, black, etc.)
Requirements from Git / local path
git+https://github.com/pallets/flask.git
-e .
Then install:
pip install -r requirements.txt
Debian / system Python warning (important)
On Debian-based systems, don’t install globally unless you know what you’re doing:
❌ Bad:
sudo pip install -r requirements.txt
✅ Good:
python3 -m venv venv
pip install -r requirements.txt
Typical workflow (TL;DR)
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python app.py