or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

backends.mdcontrol-requests.mddevice-communication.mddevice-discovery.mdindex.mdlegacy-api.mdutilities.md
tile.json

tessl/pypi-pyusb

Easy USB access for Python with backend-neutral, cross-platform support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyusb@1.3.x

To install, run

npx @tessl/cli install tessl/pypi-pyusb@1.3.0

index.mddocs/

PyUSB

A comprehensive Python library that provides easy access to Universal Serial Bus (USB) devices for Python applications. PyUSB offers a backend-neutral, API-rich interface that abstracts the complexities of USB communication while supporting multiple USB backends including libusb 1.0, libusb 0.1, and OpenUSB.

Package Information

  • Package Name: pyusb
  • Language: Python
  • Installation: pip install pyusb
  • Python Versions: Python >= 3.9
  • Platforms: Linux, Windows, macOS, BSD

Core Imports

import usb.core
import usb.util

For device discovery and basic operations:

import usb.core

# Find devices
device = usb.core.find(idVendor=0x1234, idProduct=0x5678)

For control requests:

import usb.control

Legacy compatibility (0.x version):

import usb  # Imports legacy API automatically

Basic Usage

import usb.core
import usb.util

# Find USB device by vendor and product ID
device = usb.core.find(idVendor=0x1234, idProduct=0x5678)

if device is None:
    raise ValueError('Device not found')

# Set device configuration (usually needed)
device.set_configuration()

# Get device configuration
config = device.get_active_configuration()

# Find the first interface and its first endpoint
interface = config.interfaces()[0]
endpoint = interface.endpoints()[0]

# Read data from endpoint
try:
    data = device.read(endpoint.bEndpointAddress, 64, timeout=1000)
    print(f"Read {len(data)} bytes: {data}")
except usb.core.USBTimeoutError:
    print("Read timeout")

# Write data to endpoint (if it's an OUT endpoint)
if usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_OUT:
    bytes_written = device.write(endpoint.bEndpointAddress, b'Hello USB!', timeout=1000)
    print(f"Wrote {bytes_written} bytes")

Architecture

PyUSB is organized around several key components:

  • Core API (usb.core): Modern, recommended interface for USB operations centered around the Device class
  • Legacy API (usb.legacy): Backward compatibility with PyUSB 0.x versions
  • Backend System: Pluggable backends supporting multiple USB libraries (libusb 1.0, libusb 0.1, OpenUSB)
  • Utility Functions (usb.util): Helper functions for endpoint handling, interface management, and device operations
  • Control Requests (usb.control): Standard USB control transfer functions

The Device class serves as the primary interface, providing methods for configuration, communication, and resource management while abstracting backend-specific details.

Capabilities

Device Discovery and Management

Find and enumerate USB devices using flexible filtering criteria, with support for device iteration and backend selection.

def find(find_all=False, backend=None, custom_match=None, **args):
    """
    Find USB devices matching criteria.
    
    Parameters:
    - find_all: bool, return all matches instead of first match
    - backend: USB backend to use
    - custom_match: callable for custom matching logic
    - **args: device descriptor fields to match (idVendor, idProduct, etc.)
    
    Returns:
    Device or list of devices
    """

def show_devices(verbose=False, **kwargs):
    """Display information about available USB devices."""

Device Discovery

Device Communication

Core device operations including configuration, data transfer, and endpoint communication with comprehensive error handling.

class Device:
    # Communication methods
    def read(self, endpoint, size_or_buffer, timeout=None):
        """Read data from endpoint."""
        
    def write(self, endpoint, data, timeout=None): 
        """Write data to endpoint."""
        
    def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength=None, timeout=None):
        """Perform control transfer."""
    
    # Configuration methods    
    def set_configuration(self, configuration=None):
        """Set device configuration."""
        
    def get_active_configuration(self):
        """Get current active configuration."""
        
    def set_interface_altsetting(self, interface=None, alternate_setting=None):
        """Set alternate setting for interface."""
        
    # Device information properties
    @property
    def langids(self):
        """Get supported language ID codes."""
        
    @property 
    def serial_number(self):
        """Get device serial number string."""
        
    @property
    def product(self):
        """Get device product string."""
        
    @property  
    def manufacturer(self):
        """Get device manufacturer string."""
        
    @property
    def parent(self):
        """Get parent device."""
        
    @property
    def backend(self):
        """Get backend being used."""
    
    # Device management
    def configurations(self):
        """Get tuple of device configurations."""
        
    def clear_halt(self, ep):
        """Clear halt/stall condition for endpoint."""
        
    def reset(self):
        """Reset device."""
        
    # Kernel driver management
    def is_kernel_driver_active(self, interface):
        """Check if kernel driver is active on interface."""
        
    def detach_kernel_driver(self, interface):
        """Detach kernel driver from interface."""
        
    def attach_kernel_driver(self, interface):
        """Re-attach kernel driver to interface."""

Device Communication

USB Control Requests

Standard USB control transfer operations for device configuration and status management.

def get_status(dev, recipient, index=0):
    """Get recipient status."""

def clear_feature(dev, feature, recipient, index=0):
    """Clear a recipient feature."""
    
def set_feature(dev, feature, recipient, index=0):
    """Set a recipient feature."""
    
def get_descriptor(dev, desc_size, desc_type, desc_index=0, langid=None):
    """Get a device descriptor."""
    
def set_configuration(dev, config):
    """Set device configuration."""

Control Requests

Utility Functions

Helper functions for endpoint handling, interface management, descriptor parsing, and resource cleanup.

def endpoint_address(address):
    """Return endpoint absolute address."""
    
def endpoint_direction(address):
    """Return endpoint transfer direction."""
    
def find_descriptor(desc, find_all=False, custom_match=None, **args):
    """Find inner descriptor."""
    
def claim_interface(device, interface):
    """Explicitly claim an interface."""
    
def get_string(dev, index, langid=None):
    """Retrieve string descriptor from device."""

Utilities

Backend System

Pluggable backend architecture supporting multiple USB libraries with automatic backend detection and configuration.

class IBackend:
    """Abstract backend interface."""
    
def get_backend():
    """Get backend instance, automatically selecting libusb1, libusb0, or openusb."""

Backends

Legacy Compatibility API

Backward-compatible API matching PyUSB 0.x interface patterns with extensive USB constants and legacy device handling.

def busses():
    """Return list of buses (legacy API)."""
    
class Device:
    """Legacy device representation."""
    
class DeviceHandle:
    """Legacy device handle."""

Legacy API

Types

class USBError(IOError):
    """Base exception for USB operations."""

class USBTimeoutError(USBError):
    """USB operation timeout error."""
    
class NoBackendError(ValueError):
    """No USB backend available error."""

class Configuration:
    """USB configuration descriptor."""
    bConfigurationValue: int
    iConfiguration: int
    bmAttributes: int
    bMaxPower: int

class Interface:
    """USB interface descriptor."""
    bInterfaceNumber: int
    bAlternateSetting: int
    bNumEndpoints: int
    bInterfaceClass: int
    bInterfaceSubClass: int
    bInterfaceProtocol: int
    iInterface: int

class Endpoint:
    """USB endpoint descriptor."""
    bEndpointAddress: int
    bmAttributes: int
    wMaxPacketSize: int
    bInterval: int

Constants

# USB Speed Constants
SPEED_UNKNOWN = 0
SPEED_LOW = 1
SPEED_FULL = 2
SPEED_HIGH = 3
SPEED_SUPER = 4

# Descriptor Type Constants
DESC_TYPE_DEVICE = 0x01
DESC_TYPE_CONFIG = 0x02
DESC_TYPE_STRING = 0x03
DESC_TYPE_INTERFACE = 0x04
DESC_TYPE_ENDPOINT = 0x05

# Endpoint Direction Constants
ENDPOINT_IN = 0x80
ENDPOINT_OUT = 0x00

# Endpoint Type Constants
ENDPOINT_TYPE_CTRL = 0x00
ENDPOINT_TYPE_ISO = 0x01
ENDPOINT_TYPE_BULK = 0x02
ENDPOINT_TYPE_INTR = 0x03

# Control Transfer Constants
CTRL_OUT = 0x00
CTRL_IN = 0x80

CTRL_TYPE_STANDARD = 0x00
CTRL_TYPE_CLASS = 0x20
CTRL_TYPE_VENDOR = 0x40
CTRL_TYPE_RESERVED = 0x60

CTRL_RECIPIENT_DEVICE = 0
CTRL_RECIPIENT_INTERFACE = 1
CTRL_RECIPIENT_ENDPOINT = 2
CTRL_RECIPIENT_OTHER = 3