PyUSB
PyUSB provides easy USB access for Python, abstracting away the low-level details of USB communication. It allows Python applications to interact with USB devices on various operating systems. The current version is 1.3.1, and it receives updates to fix bugs and maintain compatibility, though releases are not on a fixed schedule.
Warnings
- gotcha PyUSB is a wrapper around a low-level USB library (e.g., libusb-1.0), which must be installed separately on your system. PyUSB will not function without a compatible backend.
- gotcha On Linux, accessing USB devices often requires root privileges or specific udev rules to grant non-root users access. Without correct permissions, `usb.core.find()` will fail to locate devices.
- breaking As of PyUSB 1.3.0, the minimum required Python version is 3.9. Attempting to install or run PyUSB 1.3.0+ on older Python versions (e.g., 3.8, 3.7, 3.6) will result in installation failures or runtime errors.
- breaking Version 1.3.0 introduced a regression in `ctrl_transfer` where supplied read buffers were discarded, potentially leading to incorrect or unexpected behavior when pre-allocating buffers for control reads. This was fixed in 1.3.1.
- gotcha The hashability of `Device` objects was broken in PyUSB 1.2.0, making them unsuitable for use in sets or as dictionary keys. This was restored in 1.2.1. Additionally, `Device.__eq__()` was implemented in 1.2.0, changing how device objects are compared.
Install
-
pip install pyusb
Imports
- core
import usb.core
- util
import usb.util
- backend
import usb.backend.libusb1 as libusb1
Quickstart
import usb.core
import usb.util
# Find the first USB device available.
# For a real application, you'd specify idVendor and idProduct, e.g.,
# dev = usb.core.find(idVendor=0x046d, idProduct=0xc077) # Example: Logitech mouse
dev = usb.core.find() # Finds any device
if dev is None:
print("No USB device found. Ensure a device is connected and permissions are set.")
else:
print(f"Device found: Bus {dev.bus}, Address {dev.address}")
try:
# Try to get manufacturer and product strings
# These indices (iManufacturer, iProduct) might be 0 or invalid on some devices
manufacturer = usb.util.get_string(dev, dev.iManufacturer)
product = usb.util.get_string(dev, dev.iProduct)
print(f" Manufacturer: {manufacturer}")
print(f" Product: {product}")
except Exception as e:
print(f" Could not read device strings (permissions or device issue): {e}")
# Always remember to dispose resources when done with the device
usb.util.dispose_resources(dev)
print("Resources disposed.")