Registry / communication / pyserial

pyserial

JSON →
library3.5pypypi✓ verified 27d ago

PySerial is a widely used, cross-platform Python library that provides essential functionality for serial port communication. It allows Python scripts to easily interact with a broad range of hardware devices, including microcontrollers (like Arduino and Raspberry Pi), GPS modules, industrial sensors, and other serial-enabled peripherals across Windows, Linux, and macOS. Currently at version 3.5, PySerial maintains an active development cycle, releasing bug fixes and minor feature updates periodically.

pip install pyserial
INSTALL
IMPORT
SIG · PYSERIAL
P
pyserial
communicationpythonv3.5
Install
1.6s avg
Import
10ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.5 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.010s · 18.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.004s · 19MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Serial
from serial import Serial
import serial

This quickstart demonstrates how to open, configure, write to, and read from a serial port using PySerial. It includes error handling and ensures the port is closed. Remember to replace `'COM_PORT_HERE'` with your actual serial port name and adjust `baudrate` as needed for your device. Data sent and received must be handled as `bytes` in Python 3.

import serial import time # Configure the serial port # Replace 'COM3' with your actual serial port ('/dev/ttyUSB0' on Linux, 'COMx' on Windows) # Ensure baudrate matches your device ser = serial.Serial( port='COM_PORT_HERE', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1 # Read timeout in seconds ) try: if not ser.is_open: ser.open() print(f"Serial port {ser.name} opened successfully.") # Write data (must be bytes in Python 3) message_to_send = b"Hello, device!\n" ser.write(message_to_send) print(f"Sent: {message_to_send.decode().strip()}") time.sleep(0.1) # Give the device some time to respond # Read data received_data = ser.readline() # Reads until newline or timeout if received_data: print(f"Received: {received_data.decode().strip()}") else: print("No data received within timeout.") except serial.SerialException as e: print(f"Serial port error: {e}") except Exception as e: print(f"An unexpected error occurred: {e}") finally: if ser.is_open: ser.close() print("Serial port closed.")
pyserial --version
Debug
Known issues
breakingPython 2.x vs. Python 3.x String Handling: PySerial 3.x requires `bytes` objects for write operations (e.g., `ser.write(b'data')`). Direct string literals (`'data'`) will cause errors in Python 3.x, unlike Python 2.x where strings were byte sequences.
fix
Ensure all data written to the serial port is encoded as `bytes` (e.g., `b'your data'` or `my_string.encode('utf-8')`). Data read from the port will also be `bytes` and may need to be decoded (`received_data.decode('utf-8')`).
affects: 3.0+
breakingRemoval of `serial.aio`: Asynchronous I/O support (`serial.aio`) was removed from the core PySerial library in version 3.2.1.
fix
For asynchronous serial communication, install the separate `pyserial-asyncio` library (`pip install pyserial-asyncio`) and use its API.
affects: 3.2.1+
deprecatedDeprecated methods `inWaiting()` and `isOpen()`: These methods were deprecated in favor of more Pythonic attribute names.
fix
Use `ser.in_waiting` (integer, number of bytes in input buffer) instead of `ser.inWaiting()` and `ser.is_open` (boolean) instead of `ser.isOpen()`.
affects: 3.0+
gotcha`readline()` without a timeout can block indefinitely: If a timeout is not set on the `Serial` object, `readline()` will block until a newline character is received, which can lead to unresponsive applications if the device does not send one.
fix
Always set a `timeout` parameter (e.g., `timeout=1`) when initializing `serial.Serial`. This will cause `readline()` to return after the specified duration if no data or newline is received.
affects: All versions
breakingRemoval of `serial.device()`: The function `serial.device()` for listing ports was removed.
fix
Use `serial.tools.list_ports` module for port enumeration. For example, `from serial.tools import list_ports; ports = list_ports.comports()`.
affects: 3.0+
gotcha`serial.serialutil.SerialException: [Errno 2] No such file or directory` during port opening: This error occurs when the specified serial port name (e.g., 'COM_PORT_HERE') does not correspond to an actual, available serial port on the system, or if the user lacks permissions to access it.
fix
Ensure the serial port name is correct and the physical (or virtual) device is connected. On Windows, ports are typically 'COM1', 'COM2', etc. On Linux/macOS, they are usually '/dev/ttyUSB0', '/dev/ttyACM0', '/dev/ttyS0', etc. You can list available ports using `from serial.tools import list_ports; for port in list_ports.comports(): print(port.device)`.
affects: All versions
gotchaAttempting to open a non-existent or inaccessible serial port via `serial.Serial()` will result in a `SerialException` (often a `FileNotFoundError` on Linux/macOS or `PermissionError`) because the specified port cannot be found or opened by the operating system. This is a common issue when the port name is incorrect or no physical/virtual port is available, or due to insufficient user permissions.
fix
Verify that the `port` string provided to `serial.Serial()` exactly matches an existing serial port on your system (e.g., `/dev/ttyUSB0` on Linux, `COM1` on Windows). Use `serial.tools.list_ports.comports()` to programmatically list available ports. Ensure the user running the application has appropriate permissions to access the serial port (e.g., is part of the `dialout` group on Linux). If running in a container or VM, ensure serial devices are correctly mapped or virtual ports are set up.
affects: All versions
Upgrade
Version history
3.5latest on PyPI · released Nov 23, 2020
Audit
Dependencies
pyserial-asynciooptionalRequired for asynchronous (async/await) serial port operations, as this functionality was moved out of the main PySerial library.
Agent activity
98 hits · last 30 days
node
94
OpenAI (training)
1
Resources
pyserial — pip install pyserial · libregistry