Listing available com ports with Python
This is the code I use.
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.
import sysimport globimport serialdef serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return resultif __name__ == '__main__': print(serial_ports())
Basically mentioned this in pyserial documentationhttps://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports
import serial.tools.list_portsports = serial.tools.list_ports.comports()for port, desc, hwid in sorted(ports): print("{}: {} [{}]".format(port, desc, hwid))
Result :
COM1: Communications Port (COM1) [ACPI\PNP0501\1]
COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]
You can use:
python -c "import serial.tools.list_ports;print serial.tools.list_ports.comports()"
Filter by know port:python -c "import serial.tools.list_ports;print [port for port in serial.tools.list_ports.comports() if port[2] != 'n/a']"
See more info here:https://pyserial.readthedocs.org/en/latest/tools.html#module-serial.tools.list_ports