Python on the Edge

My latest project involves running Python not only in the cloud (with Django and PostgreSQL) but also on remote edge devices (Raspberry Pis). When you’re hosting a project yourself then you have a lot of control about the environment and infrastructure (particularly if using containers). However, when you don’t control the device things become more challenging.

I’ve built a systemd Python service for running on a Raspberry Pi that also handles auto-updates including validating the new updated software. For some of the functions it’s useful to know details about the underlying runtime, architecture and hardware capabilities.

Here is a little bit of code to retrieve the Python version, platform, hardware model and OS version.

import platform
import sys

python_version: str = ""
python_platform: str = ""
hw_model: str = ""
os_version: str = ""

try:
    python_version = sys.version
    python_platform = platform.platform()
    f = open("/proc/cpuinfo", "r")
    for line in f:
        if line.startswith("Model"):
            hw_model = line.split(": ")[1][:-1]
    f.close()
    f = open("/etc/debian_version", "r")
    os_version = f.readline()[:-1]
    f.close()
except Exception as ex:
    print(f"Unexpected error: {ex}")
    pass

Newline characters are removed from the end of the file reads with [:-1]. The newline in the middle of sys.version has been left. The values should look something like the following, depending on the hardware and OS.

3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110]

Linux-5.10.92-v8+-aarch64-with-glibc2.31

Raspberry Pi 4 Model B Rev 1.4

11.2

You can get more info from the cpuinfo file by looking for Hardware, Revision or Serial. You can also look in /etc/os-release (/etc/lsb-release is not available) and will see something like this.

PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

The nice thing about the latest Raspberry Pi OS release is that it reports as full debian. This means software that doesn’t recognize raspbian still works, as previously it looked more like this:

ID=raspbian
ID_LIKE=debian

There are other methods on platform that can be useful. E.g. platform.machine() returns the architecture such as aarch64 (the same as platform.uname().machine). This is the Python equivalent of running uname -m in a bash terminal.


Would you like help solving a technology problem in your business?
Email me for a free consultation. I'm always open to new opportunities!

This blog is treeware! If you found it useful then please plant a tree.
Donate a treeDonate a tree🌳🌳