Skip to main content

Python, the venv and Thonny

The labs use three extra Python libraries: pyserial (import serial), pymysql and flask. They live in a virtual environment (venv) called env in /home/pi. Nearly every Python problem in the labs is really "the wrong Python is running".

Why a venv at all?​

Raspberry Pi OS uses Python for its own tools. To stop pip from breaking them, Bookworm blocks pip install outside a venv:

error: externally-managed-environment

A venv is a folder with its own copy of the Python command and its own packages. Installing into it cannot break the system.

:::warning Do not use --break-system-packages The error message suggests it. It works, until an update breaks your system Python or your packages. Use the venv. :::

Two Pythons on one Pi​

System Pythonvenv Python
Path/usr/bin/python3/home/pi/env/bin/python3
Has gpiozeroYesOnly if made with --system-site-packages
Has pyserial, pymysql, flaskNoYes, after pip install
pip install allowedNo (externally-managed)Yes

ModuleNotFoundError: No module named 'serial' means your code ran with the system Python, or with a venv where pyserial was never installed. Find out which Python is running by putting this at the top of the script:

import sys; print(sys.executable)

The venv in the terminal​

cd /home/pi
source env/bin/activate # turn the venv on: the prompt starts with (env)
which python # /home/pi/env/bin/python = good
pip list # what is installed in this venv
deactivate # turn it off

Activation only lasts for that terminal window. A new terminal, a reboot or an SSH session needs source env/bin/activate again.

You can skip activating by calling the venv's Python directly:

/home/pi/env/bin/python myscript.py

The venv in Thonny​

Thonny does not care what you activated in the terminal. It has its own setting:

  1. Tools → Options → Interpreter (no Tools menu? click Switch to regular mode at the top right and restart Thonny).
  2. Choose Alternative Python 3 interpreter or virtual environment.
  3. Set the path to /home/pi/env/bin/python3.

The bottom-right corner of Thonny shows which interpreter is in use. Check it whenever you get ModuleNotFoundError.

Rebuilding a broken venv​

A venv is disposable: if it is broken (after a crash, a card repair or a strange pip error), delete it and make a new one. Your .py files are not inside it, so they are safe.

cd /home/pi
rm -rf env
python3 -m venv --system-site-packages env
source env/bin/activate
pip install pyserial pymysql flask

--system-site-packages lets the venv also use the system's packages (such as gpiozero). Then set Thonny's interpreter again.

Running scripts​

HowStop it with
Thonny: Run (F5)Red Stop button (Ctrl+F2)
Terminal: python myscript.pyCtrl+C

A script that reads the serial port or runs Flask keeps running until you stop it. Running it a second time while the first is still running gives Device or resource busy or Address already in use. Stop the old one first. To find a forgotten one:

ps aux | grep python # find the process number (PID)
kill 1234 # stop it (use the real PID)

Reading a Python error​

Python prints a traceback. Read it from the bottom:

Traceback (most recent call last):
File "/home/pi/Lab5diii.py", line 14, in <module> <- your file and line number
Temp = float(Temp)
ValueError: could not convert string to float: '' <- what went wrong

The last line is the error. The line above that names your file and the line to look at.

Common errors​

ErrorCauseFix
externally-managed-environmentpip outside the venvsource /home/pi/env/bin/activate first
ModuleNotFoundError: No module named 'serial' / 'pymysql' / 'flask'Wrong interpreter, or not installed in the venvCheck Thonny's interpreter; pip install inside the venv
ModuleNotFoundError: No module named 'gpiozero' (in the venv)venv made without system packagesRebuild with --system-site-packages
ImportError: cannot import name 'Serial' from 'serial'The wrong package called serial is installed, or your own file is named serial.pypip uninstall serial then pip install pyserial; never name your script after a library (serial.py, flask.py)
IndentationError: expected an indented blockIndentation lost when copying from a PDFRe-indent with 4 spaces (Thonny: select lines, Tab)
TabError: inconsistent use of tabs and spacesMixed tabs and spacesThonny: Edit → Replace tabs with 4 spaces, or retype the indentation
SyntaxError: invalid character '’'Smart quotes from a PDFRetype the quotes as ' or "
SyntaxError: source code cannot contain null bytesFile damaged by a power cutRepair
bash: env/bin/activate: No such file or directoryNot in /home/pi, or no venv yetcd /home/pi, or create it