What is the cross-platform method of enumerating serial ports in Python (including virtual ports)? What is the cross-platform method of enumerating serial ports in Python (including virtual ports)? python python

What is the cross-platform method of enumerating serial ports in Python (including virtual ports)?


This is what I've been using. It's a mashup of the methods I posted above. I'd still like to see better solutions, though.

# A function that tries to list serial ports on most common platformsdef list_serial_ports():    system_name = platform.system()    if system_name == "Windows":        # Scan for available ports.        available = []        for i in range(256):            try:                s = serial.Serial(i)                available.append(i)                s.close()            except serial.SerialException:                pass        return available    elif system_name == "Darwin":        # Mac        return glob.glob('/dev/tty*') + glob.glob('/dev/cu*')    else:        # Assume Linux or something else        return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')


bitpim had quite a bit of code for comscan on multiple platforms. Probably useful to get some code out of there to build a cross platform serial port enumerator. You can run the detection code directly in command line to test it out.

Link to source file comscan.py.

In Linux, it didn't seem to detect '/dev/ttyS' ports. Adding the following line below line #378 worked:

("/dev/ttyS", "Standard Serial Port", "serial"),

The author has made it easy to add different kind of identifiers for serial ports.

In Mac, it worked just fine. (Had an Arduino handy to test)

In Windows, it successfully detected the connected port (for the connected FTDI connector). Requires pywin32.

With pyserial, I tried the following:

python -m serial.tools.list_ports

Does not seem to work on Windows. Works on Mac. Works on Linux.

It is interesting to see the Platform section in the documentation for this command:

Platform :  Posix (/dev files)Platform :  Linux (/dev files, sysfs and lsusb)Platform :  Windows (setupapi, registry)

I think an amalgamation of the two should give an (almost) 100% reliable com port enumerator.

Edit: Tried all of the above in Python 2.7.