DeaD_EyE icon

Get CPU Serial from Raspberry Pi

DeaD_EyE | PRO | 07/18/22 04:57:11 PM UTC | 0 ⭐ | 1617 👁️ | Never ⏰ | []
Python |

1.2 KB

|

None

|

0 👍

/

0 👎

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

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎