pySerial
pySerial is a popular Python library for serial port communication. It is cross-platform and supports Windows, macOS, Linux and BSD.1
Installation
Install pySerial using a package manager such as pip or uv. For example, to install using uv:
uv add pySerialListing Available Serial Ports
To list the available serial ports, you can use the serial.tools.list_ports.comports() function. For example:
import serial.tools.list_portsports = serial.tools.list_ports.comports()for port in ports: print(port.device)Opening a Serial Port
To open a serial port, you can use the serial.Serial() constructor. For example:
import serialser = serial.Serial('/dev/ttyUSB0')The serial.Serial() constructor takes a number of arguments, including the port name, baud rate, timeout, e.t.c. The most common arguments are:
port: The port name to open.baudrate: The baud rate to use.timeout: The timeout in seconds.
If you don’t specify a port name, pySerial will create a port object that is in the closed state, and you’ll need to manually open it using the open() method.
Reading and Writing to a Serial Port
To read from a serial port, you can use the read() method. For example:
data = ser.read(100)This reads up to 100 bytes from the serial port.
Examples
Quick Write Example
import serialser = serial.Serial('/dev/ttyUSB0') # open serial portser.write(b'hello') # write a stringser.close() # close portFootnotes
-
pySerial. pySerial Documentation - Homepage. Retrieved 2026-01-23, from https://pyserial.readthedocs.io/en/latest/. ↩
-
pySerial. pySerial Documentation - Short Introduction. Retrieved 2026-01-23, from https://pyserial.readthedocs.io/en/latest/shortintro.html. ↩