Access USB serial ports using Python and pyserial

Viewed 44554

How do I access the USB port using pyserial? I have seen an example with:

import serial

ser = serial.Serial('/dev/ttyUSB0')

I used to access the serial port from MATLAB on Windows and using the appropriate syntax, /dev/ttyUSB0 would be replaced by COM1 or any other COM port.

I'm on a Mac and I tried using the serial port scanners on the pyserial documentation to no avail. I think I should write it like this:

import serial

name = ? # Names of serial ports on Mac OS X
ser = serial.Serial(name)

How do I find out what name should be on a Mac?

EDIT: In response to an answer below, I'd like to find out how to access both USB to RS232 converters as well as pure USB ports.

2 Answers

To find the available ports you can use serial.tools (which is part of the pyserial library, but needs to be imported separately). The device name can then be found using the .device method. This works for me on Mac:

from serial.tools import list_ports
port = list(list_ports.comports())
for p in port:
    print(p.device)

For more on list_ports, see: https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports

Related