The course
Automate it with Python is an intermediate Coding course in seven lessons on the gallery's Raspberry Pi builds: the two-LED board (red on GPIO17, yellow on GPIO27) for jobs that blink a lamp, the button board for the watched folder, and a Pi Zero 2 W with a BME280 for the boss. Each step is checked against what the Pi prints or which LED it blinks.
- Scripts and argparse:
sys.argv, a parser with a positional, options, types, choices and defaults, an LED blinked by the arguments,--helpfor free, clear errors, and arguments typed in the Serial Monitor. - Bulk renaming: microscope photos with messy names, a regular expression that reads them, a plan before any change, conflicts found before they overwrite a photo, a dry run, and an undo log in JSON.
- Logging: levels and formats, filtering by level, named loggers, a
log file that keeps only warnings and worse, and tracebacks with
log.exception. - Scheduling on the clock: a sleep loop that drifts (run 4 at 3.9 s), a
fixed-rate schedule that does not (3.0 s), several jobs at different
rates, the next 09:00 worked out with
datetime, and a clean stop on Ctrl-C. - Watching a folder: the button is an instrument that drops sample files; a polling watcher spots them with set difference, processes each once and moves it to done/, and sends bad files to errors/.
- Reports: a class's yeast and sugar experiment turned into means, a
Markdown table in report.md, highlights, and a note from a
string.Template. - Boss: a lab notebook bot: the finale.
The finale
The bot keeps a lab notebook from commands typed in the Serial Monitor:
note TEXT adds a stamped line to notebook.md, measure --count N --every S (its own argparse parser) logs the live temperature to readings.csv on a
fixed-rate schedule, a bad option is logged as a warning without stopping
the bot, report writes report.md with the mean, the range and the notes,
and a reading above 35 C raises a logged alarm.
The catalog names a DS18B20 thermometer. The Pi engine has no 1-Wire bus, so the gallery's BME280, its only temperature sensor on a Pi, stands in.
What the Pi's engine does differently
The Pi runs MicroPython 1.29 with a CPython-style standard library:
- Run passes no arguments, so
sys.argvis['main.py']. The lessons handparse_argsa list, exactly what it would get from a terminal. - argparse has no subcommands (
add_subparsers), andSystemExithas no.code, so the bot gives each command its own parser. time.sleepandtime.monotonicrun on the simulated clock, so the schedules are exact and the same every run.time.timeanddatetime.now()start at the real time, so nothing checked depends on the date.- A file's modification time does not change when it is written, so the watcher works from file names.
logging.handlersis not there;FileHandleris.- Files last while the program runs, so the starters make their own folders of files to work on.