Python and Raspberry Pi
This documentation provides guidance on installing and managing Python packages on Raspberry Pi OS, with a focus on using Python virtual environments.
Python 3 is pre-installed on Raspberry Pi OS and is crucial for many system functions.
It's important not to interfere with the system Python installation when installing third-party libraries.
There are two ways to install Python libraries on Raspberry Pi OS:
Using
apt
to install pre-configured system packages (preferred method).Using
pip
to install packages not distributed as part of Raspberry Pi OS.
From the Bookworm version onwards, packages installed via pip
must be installed into a Python virtual environment using venv
.
This change was introduced by the Python community to avoid conflicts between OS package managers and Python-specific package management tools.
To create a virtual environment for each Python project
Create a project directory and navigate into it.
Create a virtual environment using
python -m venv env
.Activate the virtual environment using
source env/bin/activate
.Install packages using
pip
within the activated virtual environment.Deactivate the virtual environment using
deactivate
.
Alternatively, you can create a single virtual environment for your user account
Create a virtual environment in your home directory using
python -m venv ~/.env
.Activate the virtual environment using
source ~/.env/bin/activate
.Install packages using
pip
within the activated virtual environment.Deactivate the virtual environment using
deactivate
.Using virtual environments ensures that third-party packages are installed separately from the system Python, avoiding potential conflicts and issues with the operating system.
The documentation emphasises the importance of using virtual environments when installing Python packages on Raspberry Pi OS, especially from the Bookworm version onwards, to maintain a clean and stable system Python installation.
Last updated
Was this helpful?