开发者

pyserial enumerate ports

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 Iterat开发者_C百科ionError

pyserial enumerate ports


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


You're raising an IterationError, but that exception doesn't actually exist. Maybe you should try raising EnvironmentError for that condition as well.

The pySerial docs include some sample code for finding serial ports. Check them out: http://pyserial.sourceforge.net/examples.html#finding-serial-ports


Below you find my helper function to print the names and description of the available com ports, using the serial module:

from serial.tools import list_ports
print(
    "\n".join(
        [
            port.device + ': ' + port.description
            for port in list_ports.comports()
        ]))

Example output:

python.exe -u listSerialPorts.py
COM4: Sierra Wireless NMEA Port (COM4)
COM12: USB Serial Port (COM12)
COM10: USB Serial Port (COM10)
COM3: Intel(R) Active Management Technology - SOL (COM3)
COM5: Sierra Wireless DM Port (COM5)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜