Why Compile from Source?
- Pin older library versions that still supported Python 3.9
- Pull Python from a third-party source. The usual suggestion online is the deadsnakes PPA, but that is built for Ubuntu rather than Debian, so it wasn't a clean fit and it brings its own trust questions
- Compile Python 3.11 directly from the CPython source
The Hardware Reality
Getting the Source
Bash
wget https://www.python.org/ftp/python/3.11.x/Python-3.11.x.tgz
tar -xzf Python-3.11.x.tgz
cd Python-3.11.x
Dependencies
Bash
sudo apt update
sudo apt install -y build-essential libssl-dev libffi-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev libncurses5-dev \
libgdbm-dev libnss3-dev liblzma-dev uuid-dev tk-dev
The Configuration Step
Bash
./configure --enable-optimizations
Bash
./configure --prefix=/usr/local --without-ensurepip
Bash
./configure --prefix=/usr/local --without-ensurepip CFLAGS="-O2"
Controlling Parallel Jobs
Bash
# Avoid this on constrained hardware
make -j$(nproc)
# Use a limited job count instead
make -j2
Thermal Management During Compilation
Bash
watch -n 5 cat /sys/class/thermal/thermal_zone0/temp
- Reduce the -j count further
- Add a heatsink if there isn't one
- Run the build when the room is cooler
- Pause the build with Ctrl+Z, let the Pi cool down, then resume with fg
Installing Without Overwriting the System Python
Bash
sudo make altinstall
Bash
python3.11 --version
# Python 3.11.x
which python3.11
# /usr/local/bin/python3.11
which python3
# /usr/bin/python3 ← still the system Python 3.9
Virtual Environments for Project Dependencies
Bash
python3.11 -m venv <venv-path>
source <venv-path>/bin/activate
pip install SpeechRecognition RPi.GPIO pigpio
Persistent Operation with tmux
Bash
tmux new-session -d -s <session-name> 'source <venv-path>/bin/activate && python3.11 <path-to-script>'
Bash
tmux attach -t <session-name>
Bash
crontab -e
# Add
@reboot sleep 10 && tmux new-session -d -s <session-name> 'source <venv-path>/bin/activate && python3.11 <path-to-script>'