Raspberry Pi OS manages Python packages a bit differently to some Linux installs and will insist on using a virtual environment (e.g. you get an error: “error: externally-managed-environment”)

Creating a virtual environment is good practice anyway for Python development in general, as it helps to manage dependencies and avoid conflicts.

pip

You have to use a virtual environment under Raspberry Pi OS when using pip to install packages, the OS will block you without one.

Create virtual environment

If virtualenv hasn’t been installed in the OS before:

sudo apt-get update && sudo apt-get upgrade
sudo apt-get install virtualenv

Create the venv (done once per venv)

Name

“venv” is often used, but it doesn’t matter, it can be anything

Creating it

Navigate to the directory where you want the virtual environment to be created.

Create a virtual environment called “venv”:

python3 -m virtualenv venv --system-site-packages

The “–system-site-packages” is an optional argument which means that the virtual environment will also have access to the system site-packages dir (see here)

Activate the virtual environment (done every time a venv is to be used)

source venv/bin/activate

Use the virtual environment (run your Python code here)

Once the virtual environment has been activated Python is used as normal. Running python or pip will be done in the context of the virtual environment. Modules installed with pip will be placed in the local venv folders (sudo should not be used).

Install a package using pip
/home/pathtovenvfolder/venv/pip3 install mypackagename
Run your app

You can copy your app files into the virtual environment if you want, for instance into a folder called \app.

Running it from the command line after activating the virtual environment:

python3 venv/app/myappname.py

Deactivate the virtual environment (optional)

deactivate

More info on virtual environments

https://learn.adafruit.com/python-virtual-environment-usage-on-raspberry-pi/automatically-running-at-boot

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *