pyserial enumerate ports

Meloun picture Meloun · May 30, 2011 · Viewed 13.5k times · Source

I need list or enumerate of existing serial ports, Till now I was using this method enumerate_serial_ports(), but its not working with windows 7. Do you know some alternative how can I find out available serial ports under windows 7?

def enumerate_serial_ports():
  """ Uses the Win32 registry to return an 
      iterator of serial (COM) ports 
      existing on this computer.
  """
  path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
  try:
      key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
  except WindowsError:
      raise IterationError

  for i in itertools.count():
      try:
          val = winreg.EnumValue(key, i)
          yield str(val[1])
      except EnvironmentError:
          break

I get IterationError enter image description here

Answer

mgalgs picture mgalgs · Jun 30, 2012

There's now a list_ports module built in to pyserial.

In [26]: from serial.tools import list_ports
In [27]: list_ports.comports()
Out[27]: 
[('/dev/ttyS3', 'ttyS3', 'n/a'),
 ('/dev/ttyS2', 'ttyS2', 'n/a'),
 ('/dev/ttyS1', 'ttyS1', 'n/a'),
 ('/dev/ttyS0', 'ttyS0', 'n/a'),
 ('/dev/ttyUSB0',
  'Linux Foundation 1.1 root hub ',
  'USB VID:PID=0403:6001 SNR=A1017L9P')]

The module can also be executed directly:

$ python -m serial.tools.list_ports
/dev/ttyS0          
/dev/ttyS1          
/dev/ttyS2          
/dev/ttyS3          
/dev/ttyUSB0        
5 ports found