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 Python | venv Python | |
|---|---|---|
| Path | /usr/bin/python3 | /home/pi/env/bin/python3 |
| Has gpiozero | Yes | Only if made with --system-site-packages |
| Has pyserial, pymysql, flask | No | Yes, after pip install |
pip install allowed | No (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:
- Tools → Options → Interpreter (no Tools menu? click Switch to regular mode at the top right and restart Thonny).
- Choose Alternative Python 3 interpreter or virtual environment.
- 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
| How | Stop it with |
|---|---|
| Thonny: Run (F5) | Red Stop button (Ctrl+F2) |
Terminal: python myscript.py | Ctrl+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
| Error | Cause | Fix |
|---|---|---|
externally-managed-environment | pip outside the venv | source /home/pi/env/bin/activate first |
ModuleNotFoundError: No module named 'serial' / 'pymysql' / 'flask' | Wrong interpreter, or not installed in the venv | Check Thonny's interpreter; pip install inside the venv |
ModuleNotFoundError: No module named 'gpiozero' (in the venv) | venv made without system packages | Rebuild 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.py | pip uninstall serial then pip install pyserial; never name your script after a library (serial.py, flask.py) |
IndentationError: expected an indented block | Indentation lost when copying from a PDF | Re-indent with 4 spaces (Thonny: select lines, Tab) |
TabError: inconsistent use of tabs and spaces | Mixed tabs and spaces | Thonny: Edit → Replace tabs with 4 spaces, or retype the indentation |
SyntaxError: invalid character '’' | Smart quotes from a PDF | Retype the quotes as ' or " |
SyntaxError: source code cannot contain null bytes | File damaged by a power cut | Repair |
bash: env/bin/activate: No such file or directory | Not in /home/pi, or no venv yet | cd /home/pi, or create it |