Linux and Python on the Pi
Python projects
sudo apt install -y python3-venv python3-pip
mkdir ~/projects/sensor && cd ~/projects/sensor
python3 -m venv .venv && source .venv/bin/activate
pip install gpiozero requests
Use a virtual environment per project; system-wide pip install is blocked on current Raspberry Pi OS to protect system packages.
Running programs at boot with systemd
# /etc/systemd/system/sensor.service
[Unit]
Description=Sensor logger
After=network-online.target
Wants=network-online.target
[Service]
User=panda
WorkingDirectory=/home/panda/projects/sensor
ExecStart=/home/panda/projects/sensor/.venv/bin/python logger.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now sensor
journalctl -u sensor -f
Scheduling
Use cron or systemd timers for periodic tasks (see Automation & Scripting).
Protecting the SD card
SD cards wear out with constant writes. Reduce logging writes, store databases on an SSD, and keep backups of important data and configuration.
Editing files remotely
Edit code on the Pi from your main computer with VS Code's Remote - SSH extension: you get the full editor, terminal and debugger while the code runs on the Pi. Commit projects to Git so the Pi is never the only copy.
Exercise
Write a Python script that logs the Pi's CPU temperature (from /sys/class/thermal/thermal_zone0/temp) every minute to a CSV, run it as a systemd service, and view its logs with journalctl.
Check yourself
- Why use a virtual environment on Raspberry Pi OS?
- How do you make a program start at boot?
- How do you reduce SD card wear?
I tuoi progressi sono salvati solo in questo browser.
Invia per la revisione (10 punti)