Page cover image

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:

  1. Using apt to install pre-configured system packages (preferred method).

  2. 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

  1. Create a project directory and navigate into it.

  2. Create a virtual environment using python -m venv env.

  3. Activate the virtual environment using source env/bin/activate.

  4. Install packages using pip within the activated virtual environment.

  5. Deactivate the virtual environment using deactivate.

Alternatively, you can create a single virtual environment for your user account

  1. Create a virtual environment in your home directory using python -m venv ~/.env.

  2. Activate the virtual environment using source ~/.env/bin/activate.

  3. Install packages using pip within the activated virtual environment.

  4. Deactivate the virtual environment using deactivate.

  5. 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?