OK serial I/O for Python 🔌〡〇〡〇〡🐍
A Python serial port library (based on PySerial) with improved port discovery and I/O semantics. (API reference)
Think twice before using this library! Consider something more established:
- good old PySerial - the implementation under
ok-serial, well established and widely used - pyserial-asyncio - official and "proper" asyncio support for PySerial
- pyserial-asyncio-fast - pyserial-asyncio fork designed for faster writes
- aioserial - alternative asyncio wrapper designed for ease of use
- bonus recommendation: tio - not a library, not Python, but a great serial terminal utility
Also see my own ok-serial-terminal, a terminal program based on this library.
Purpose
Since 2001, PySerial has been the workhorse serial port / UART library for Python. It runs most places Python does and abstracts lots of gnarly system details. However, some issues keep coming up:
-
Most modern serial ports are USB, and get temporary names like
/dev/ttyACM3orCOM4. PySerial'sserial.tools.list_ports.grep(...)or Linux's/dev/serial/by-id(or custom udev rules) are helpful but clunky. -
Nonblocking or concurrent PySerial I/O is tricky and often broken entirely.
-
PySerial has small buffers; overruns lose data and/or block unexpectedly.
-
PySerial doesn't lock ports by default, and only supports one advisory locking method. Bad things happen when multiple programs try to use the same port.
The ok-serial library uses PySerial internally but has a revised interface:
-
Ports are referenced by match strings with wildcard support (eg.
RP2040or2e43:0226) or, for by arbitrarySerialPort -> boolcallables. -
I/O operations are thread safe and can be blocking, non-blocking, timeout-based, or async. Blocking operations can be cleanly interrupted. The semantics of concurrent access, partial reads/writes, interruption, I/O errors, closure, and other edge cases are well defined.
-
I/O buffers are limited only by system memory; writes never block. (A blocking drain is available.)
-
Several port locking modes are supported, with exclusive locking by default. All of
/var/lock/LCK..*files,flock(...)(like PySerial), andTIOCEXCLare used to avoid contention. -
SerialConnectionMonitoris an automatic reconnection helper for graceful handling of pluggable devices.
Installation
pip install ok-serial
(or uv add ok-serial, etc.)
Usage
Here is a minimal example:
import ok_serial
conn = ok_serial.SerialConnection(match="MyDevice", baud=115200)
conn.write("Hello Device!")
while (data := conn.read_sync(timeout=5)):
print("Received data:", data)
print("...5 seconds elapsed with no data")
(Note that "MyDevice" is a port match expression.)
API elements worth knowing include:
SerialConnection- establish a connection to a specific port and perform I/Oscan_serial_ports- get all ports on the system, with descriptive attributesSerialConnectionMonitor- scan and connect to a port with automatic error retry
I/O methods come in different flavors:
*_syncmethods (eg.read_sync) block, accepttimeout=..., and can raise exceptions*_asyncmethods (eg.read_async) return anawait-able coroutine for asyncio- Use
asyncio.timeoutto add a timeout - Errors are reported via the coroutine (
awaitwill raise)
- Use
- Other methods (eg.
write) are non-blocking.
All methods and functions are thread-safe and thread-sane. Any error or closure on a connection interrupts all operations on that connection.
See the full API reference docs for interface details.
Serial port attributes
Serial ports have metadata attributes like descriptive text, USB vendor/product ID, serial number and the like. These are captured as key/value pairs in SerialPort.attr and returned by scan_serial_ports.
Specific attributes come from PySerial and are platform/device dependent but typically include:
device- system device name, eg./dev/ttyUSB1orCOM3description- human readable text, eg.Arduino Unomanufacturer- USB device manufacturer name, eg. `vid_pid- USB vendor and product ID, eg.0403:6001serial_number- USB device serial, eg.DF62585783553434location- system bus attachment path, eg.3-2.1:1.0
To see all the attributes, install ok-serial and run okserial -v:
Port: /dev/ttyACM3 Kq2p 3:12s
device=/dev/ttyACM3
name=ttyACM3
description='Feather RP2040 RFM - Pico Serial'
hwid='USB VID:PID=239A:812D SER=DF62585783553434 LOCATION=3-2.1:1.0'
vid=9114
pid=33069
serial_number=DF62585783553434
location=3-2.1:1.0
manufacturer=Adafruit
product='Feather RP2040 RFM'
interface='Pico Serial'
usb_device_path=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2.1
device_path=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2.1/3-2.1:1.0
subsystem=usb
usb_interface_path=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2.1/3-2.1:1.0
tid=Kq2p
time=2026-08-04T12:38:39.800
vid_pid=239a:812d
...
Port matching
SerialConnection(match=...) and SerialConnectionMonitor(...) take either a match string or a predicate callable (SerialPort -> bool).
A match string is split on whitespace into glob tokens. Each token must match (case-insensitively, as a whole-word glob with * and ? wildcards) somewhere in some attribute value. So:
Pico- some attribute contains the wordpico(any case)RP2040 DF625*- some attribute containsrp2040, and some attribute contains a word starting withdf6252e8a:0005- matches the canonicalvid_pidform (lowercase hex)ttyS1- does NOT match/dev/ttyS10; usettyS1*for prefix matching
Word boundaries treat any non-alphanumeric character (/, :, _, etc.) as a separator, so partial USB IDs and device-path fragments work naturally.
For anything more elaborate (substring matching across attribute boundaries, regex, negation, etc.), pass a callable:
ok_serial.SerialConnectionMonitor(
match=lambda p: p.attr.get("manufacturer") == "Adafruit"
and p.attr.get("serial_number", "").startswith("DF625"),
)
Sharing modes
When opening a port, SerialConnection offers a choice of sharing modes:
oblivious(not recommended) - Checks no locks and holds no locks. Multiple programs may open the port at once, leading to corruption.polite- Checks for locks before opening the port, but holds no locks while running. Abandons the port if another program is detected using it.exclusive(the default) - Checks for locks before opening the port, and holds locks to guard against other programs using the port.stomp(use with care!) - Any other program using the port is killed, if possible; locks are held, if possible; the port is opened regardless.
Sharing mode implementation is limited by OS capabilities, process permissions, and historical conventions of port usage coordination. Best efforts are taken but your mileage may vary.
Command line utility
Installing ok-serial also installs okserial, which lists the serial ports on the system:
$ okserial
🔎 Finding serial ports...
✅ 2 serial ports found
/dev/ttyACM0 ZdvG usb 0424:494c 'USB2 Controller Hub - UART Bridge' 1d+04:18:11s
/dev/ttyACM3 Kq2p usb 239a:812d 'Feather RP2040 RFM' DF62585783553434 3:12s
Each line includes the device name, tio-compatible topology ID, and whichever of the subsystem, USB vendor/product ID, description, and serial number are known, along with the age of the port.
Run okserial -v print extra detail; see okserial --help for more options.
For an interactive terminal, see ok-serial-terminal.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ok_serial-0.5.1.tar.gz.
File metadata
- Download URL: ok_serial-0.5.1.tar.gz
- Upload date:
- Size: 18.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
389f2507f26c2705bc91cd41da1d38b26b948d5b47671ede152d3d4372244832
|
|
| MD5 |
3b33178a69a723af5fa08aed5535972c
|
|
| BLAKE2b-256 |
be16eb8a4b7b2572b31c3cb3091453199d86be66bff4280f028905dd319902ef
|
File details
Details for the file ok_serial-0.5.1-py3-none-any.whl.
File metadata
- Download URL: ok_serial-0.5.1-py3-none-any.whl
- Upload date:
- Size: 22.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8a7fff8ae7be3b683e5cbed557af6ac2b8dff587029c4a5527db1763f18c86b8
|
|
| MD5 |
40d3c8dd2517a85306a6f0f0dd5a060c
|
|
| BLAKE2b-256 |
045cde4bd69754a47553f6136fef7e5ff842598a8466eff8b27c93bd73aa1143
|