from __future__ import annotations
import re
from pathlib import Path
REGEX = re.compile(r"^Serial\s+:\s+([0-9a-f]+)$", re.MULTILINE)
# with regex
def get_serial(as_hex: bool = False) -> int | str:
cpuinfo = Path("/proc/cpuinfo").read_text()
match = REGEX.search(cpuinfo)
if not match:
raise RuntimeError("This is not a Raspberry Pi")
serial = int(match.group(1), 16)
if as_hex:
serial = hex(serial)
return serial
# no regex
def get_serial(as_hex: bool = False) -> int | str:
with open("/proc/cpuinfo") as fd:
for line in fd:
if line.startswith("Serial"):
serial = int(line.rpartition(":")[2], 16)
break
else:
# This branch is only reached, if the
# for-loop has been finished
# a break in the for loop will not execute this branch
raise RuntimeError("This is not a Raspberry Pi")
if as_hex:
serial = hex(serial)
return serial
if __name__ == "__main__":
try:
print(get_serial())
print(get_serial(as_hex=True))
except RuntimeError as err:
raise SystemExit(err.args[0])
Comments
0 B
|👍
/👎