Getting Your Raspberry Pi Serial Number Using Python


Every Raspberry Pi has a unique serial number. It is sometimes useful to extract this number to identify the hardware that your Python scripts are running on.

The following function “getserial()” can be used to return a string containing the unique serial number. In reality this is the serial number of the Broadcom CPU but given you are unlikely to remove the CPU from the PCB it was supplied on this can be considered the serial of the whole device.

Here is the Python function :

def getserial():
  # Extract serial from cpuinfo file
  cpuserial = "0000000000000000"
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:6]=='Serial':
        cpuserial = line[10:26]
    cpuserial = "ERROR000000000"

  return cpuserial

If you include this definition at the beginning of your Python script you can use it to set a variable equal to the serial number :

myserial = getserial()




    • That line should have two spaces at the beginning. The spaces may have been lost if you cut and pasted. I’ve adjusted the formatting so give it a try again.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.