Source: Python Package Management
apt vs pip
| apt | pip | |
|---|---|---|
| Installs from | Debian repo | PyPI (pypi.org) |
| Packages | python3-<name> naming | Exact PyPI name |
| Stability | Tested, pre-compiled, stable | Bleeding edge, latest versions |
| Preferred for | System tools, apps | Project dev libraries |
sudo apt install python3-build-hat # apt: system-wide, stable
pip install gpiozero # pip: inside venv onlyWhy pip system-wide fails (Debian Bookworm+)
$ pip install buildhat
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to install.From Debian Bookworm onwards, pip must be used inside a virtual environment.
Virtual Environments (venv)
Why
- Avoid system pollution (don’t mix project packages with OS packages)
- Avoid version conflicts between projects
- Make projects reproducible (
requirements.txt)
The 5 commands
# 1. Create (inside project dir)
python -m venv .venv
# 2. Activate
source .venv/bin/activate
# Prompt changes to: (.venv) $
# 3. Install packages (now goes to .venv, not system)
pip install gpiozero
# 4. Deactivate
deactivate
# 5. Check installed packages
pip freezeCheck a specific package
pip show gpiozero
# Shows: Name, Version, Location, Requiresvenvs are non-portable
Virtual environments use absolute paths internally. If you move/copy the project:
- Do NOT move the
.venvfolder - Do recreate it:
pip install -r requirements.txt
Create a freeze file: pip freeze > requirements.txt
Recreate: pip install -r requirements.txt
sudo + venv problem (critical for reTerminal)
Problem: Packages like seeed-python-reterminal need root. But:
(.venv) $ sudo python ./leds.py
# ERROR: Module not found — root user uses /usr/bin/python, not .venv pythonsudo runs the root user’s Python, which doesn’t see your venv.
Solution: Point sudo to the venv’s Python explicitly:
# Using which (command substitution — recommended)
sudo $(which python) ./leds.py
# Using relative path
sudo ./.venv/bin/python ./leds.py
# Using absolute path
sudo /home/user/project/.venv/bin/python ./leds.pyVerify which Python is active: which python
sys.path (debug module not found)
import sys
print(sys.path) # list of directories Python searches for modulesIf the package’s Location (from pip show) is not in sys.path, Python can’t find it.
See Also
- Python Essentials topic
- venv concept