ABC of Electronics cosycom.com
RASPBERRY PI 16 · Python Setup

Python Virtual Environments and pip

Keep each project's Python packages separate and reproducible, instead of installing everything globally onto the same system.

You'll need: just your Pi and a terminal — this lesson is entirely about Python project hygiene.

As you follow more lessons, you'll install more Python packages with pip. Installing everything directly onto the system-wide Python can eventually cause two projects to need conflicting versions of the same package — a virtual environment (venv) solves this by giving each project its own isolated, self-contained set of installed packages.

terminal
python3 -m venv myproject-env
source myproject-env/bin/activate
pip install requests
deactivate

python3 -m venv myproject-env creates a new, empty virtual environment in a folder named myproject-env. source myproject-env/bin/activate switches your current terminal session into it — your prompt changes to show the environment's name, confirming you're inside it. From that point, pip install installs packages into this isolated environment only, not system-wide. deactivate exits back to your normal system Python.

One Raspberry Pi-specific note: the RPi.GPIO and picamera2 libraries used throughout this course sometimes need to be installed with system access to hardware, and may need an extra flag (python3 -m venv --system-site-packages myproject-env) to see those system-level packages from inside a venv — worth knowing if a GPIO import fails inside a virtual environment that works fine outside one.

Project Avenv: requests 2.x Project Bvenv: requests 1.x System Pythonuntouched by eitherabcofelectronics
Each virtual environment keeps its own package versions, isolated from other projects and from the system Python underneath.
TRY THIS
If a GPIO or camera import fails only inside a virtual environment, recreate it with --system-site-packages so it can see those hardware-linked system packages.