Source: Python Package Management

apt vs pip

aptpip
Installs fromDebian repoPyPI (pypi.org)
Packagespython3-<name> namingExact PyPI name
StabilityTested, pre-compiled, stableBleeding edge, latest versions
Preferred forSystem tools, appsProject dev libraries
sudo apt install python3-build-hat   # apt: system-wide, stable
pip install gpiozero                 # pip: inside venv only

Why 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

  1. Avoid system pollution (don’t mix project packages with OS packages)
  2. Avoid version conflicts between projects
  3. 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 freeze

Check a specific package

pip show gpiozero
# Shows: Name, Version, Location, Requires

venvs are non-portable

Virtual environments use absolute paths internally. If you move/copy the project:

  • Do NOT move the .venv folder
  • 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 python

sudo 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.py

Verify which Python is active: which python

sys.path (debug module not found)

import sys
print(sys.path)   # list of directories Python searches for modules

If the package’s Location (from pip show) is not in sys.path, Python can’t find it.

See Also