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"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:6]=='Serial':
        cpuserial = line[10:26]
    f.close()
  except:
    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()

 

This entry was posted in Hardware, Python, Tutorials & Help and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>