Advertisement
DeaD_EyE

Get CPU Serial from Raspberry Pi

Jul 18th, 2022
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. from __future__ import annotations
  2.  
  3. import re
  4. from pathlib import Path
  5.  
  6. REGEX = re.compile(r"^Serial\s+:\s+([0-9a-f]+)$", re.MULTILINE)
  7.  
  8. # with regex
  9. def get_serial(as_hex: bool = False) -> int | str:
  10.     cpuinfo = Path("/proc/cpuinfo").read_text()
  11.     match = REGEX.search(cpuinfo)
  12.     if not match:
  13.         raise RuntimeError("This is not a Raspberry Pi")
  14.  
  15.     serial = int(match.group(1), 16)
  16.  
  17.     if as_hex:
  18.         serial = hex(serial)
  19.  
  20.     return serial
  21.  
  22.  
  23. # no regex
  24. def get_serial(as_hex: bool = False) -> int | str:
  25.     with open("/proc/cpuinfo") as fd:
  26.         for line in fd:
  27.             if line.startswith("Serial"):
  28.                 serial = int(line.rpartition(":")[2], 16)
  29.                 break
  30.         else:
  31.             # This branch is only reached, if the
  32.             # for-loop has been finished
  33.             # a break in the for loop will not execute this branch
  34.             raise RuntimeError("This is not a Raspberry Pi")
  35.  
  36.     if as_hex:
  37.         serial = hex(serial)
  38.  
  39.     return serial
  40.  
  41.  
  42. if __name__ == "__main__":
  43.     try:
  44.         print(get_serial())
  45.         print(get_serial(as_hex=True))
  46.     except RuntimeError as err:
  47.         raise SystemExit(err.args[0])
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement