pyserial – Listing available com ports with Python

pyserial – 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 sys
import glob
import serial


def 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 result


if __name__ == __main__:
    print(serial_ports())

Basically mentioned this in pyserial documentation
https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports

import serial.tools.list_ports
ports = serial.tools.list_ports.comports()

for port, desc, hwid in sorted(ports):
        print({}: {} [{}].format(port, desc, hwid))

Result :

COM1: Communications Port (COM1) [ACPIPNP05011]

COM7: MediaTek USB Port (COM7) [USB VID_PID=0E8D:0003 SER=6 LOCATION=1-2.1]

pyserial – Listing available com ports with Python

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

Leave a Reply

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