[ PySerial ] 檢查 Serial設備

因為工作需求,需要使用 USB傳輸 Serial data。
之前都是用 Arduino IDE檢查 Port的位置,一直感覺手段不是很漂亮。
最近在 StackOverflow上看到有人分享一段代碼,能夠自動尋找電腦上 Serial的設備。
由於簡單給力,所以我就原封不動的 PO了。

Successfully tested on Windows 8.1 x64, Windows 10 x64, Mac OS X 10.9.x / 10.10.x / 10.11.x and Ubuntu 14.04 / 14.10 / 15.04 / 15.10 with both Python 2 and Python 3.
  1. import sys
  2. import glob
  3. import serial
  4.  
  5.  
  6. def serial_ports():
  7. """ Lists serial port names
  8.  
  9. :raises EnvironmentError:
  10. On unsupported or unknown platforms
  11. :returns:
  12. A list of the serial ports available on the system
  13. """
  14. if sys.platform.startswith('win'):
  15. ports = ['COM%s' % (i + 1) for i in range(256)]
  16. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  17. # this excludes your current terminal "/dev/tty"
  18. ports = glob.glob('/dev/tty[A-Za-z]*')
  19. elif sys.platform.startswith('darwin'):
  20. ports = glob.glob('/dev/tty.*')
  21. else:
  22. raise EnvironmentError('Unsupported platform')
  23.  
  24. result = []
  25. for port in ports:
  26. try:
  27. s = serial.Serial(port)
  28. s.close()
  29. result.append(port)
  30. except (OSError, serial.SerialException):
  31. pass
  32. return result
  33.  
  34.  
  35. if __name__ == '__main__':
  36. print(serial_ports())

原出處: Listing available com ports with Python

留言