CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-evdev

Python bindings to the Linux input handling subsystem for reading input events and creating virtual input devices

Pending
Overview
Eval results
Files

device-operations.mddocs/

Device Operations

Core functionality for discovering, opening, and interacting with Linux input devices. This includes device enumeration, capability querying, event reading, and device control operations.

Capabilities

Device Discovery

Functions for finding and identifying available input devices on the system.

def list_devices(input_device_dir: Union[str, bytes, os.PathLike] = "/dev/input") -> List[str]:
    """
    List readable character devices in input_device_dir.
    
    Parameters:
    - input_device_dir: Directory to search for input devices (default: "/dev/input")
    
    Returns:
    List of device paths (e.g., ["/dev/input/event0", "/dev/input/event1"])
    """

Device Initialization

Opening and initializing input device connections.

class InputDevice:
    def __init__(self, dev: Union[str, bytes, os.PathLike]) -> None:
        """
        Initialize InputDevice with device path.
        
        Parameters:
        - dev: Path to input device (e.g., "/dev/input/event0")
        
        Raises:
        - EvdevError: If device cannot be opened or accessed
        """
    
    def close(self) -> None:
        """Close the device file descriptor and release resources."""
    
    def fileno(self) -> int:
        """
        Return file descriptor for the device.
        Enables use with select.select() and asyncore.file_dispatcher.
        """

Device Information

Methods for querying device properties, capabilities, and status information.

class InputDevice:
    @property
    def path(self) -> str:
        """Path to the input device."""
    
    @property
    def fd(self) -> int:
        """File descriptor to the device."""
    
    @property
    def info(self) -> DeviceInfo:
        """Device identification information (vendor, product, etc.)."""
    
    @property
    def name(self) -> str:
        """Device name as reported by the kernel."""
    
    @property
    def phys(self) -> str:
        """Physical topology of the device."""
    
    @property
    def uniq(self) -> str:
        """Unique identifier for the device."""
    
    @property
    def version(self) -> int:
        """Evdev protocol version supported by the device."""
    
    @property
    def ff_effects_count(self) -> int:
        """Number of force feedback effects the device can store."""
    
    def capabilities(self, verbose: bool = False, absinfo: bool = True) -> Dict:
        """
        Get device capabilities and supported event types.
        
        Parameters:
        - verbose: Return human-readable names instead of numeric codes
        - absinfo: Include AbsInfo for absolute axes
        
        Returns:
        Dictionary mapping event types to lists of supported event codes.
        For absolute axes, includes (code, AbsInfo) tuples when absinfo=True.
        """
    
    def input_props(self, verbose: bool = False) -> List:
        """
        Get device input properties and quirks.
        
        Parameters:
        - verbose: Return human-readable names instead of numeric codes
        
        Returns:
        List of input property flags
        """

Event Reading

Methods for reading input events from devices.

class InputDevice:
    def read_loop(self) -> Iterator[InputEvent]:
        """
        Enter endless select() loop yielding input events.
        Blocks until events are available.
        """
    
    def read_one(self) -> Union[InputEvent, None]:
        """
        Read single input event from device.
        
        Returns:
        InputEvent if available, None if no events pending
        """
    
    def read(self) -> List[InputEvent]:
        """
        Read multiple input events from device.
        
        Returns:
        List of available InputEvent objects
        """

Device Control

Operations for controlling device behavior and state.

class InputDevice:
    def grab(self) -> None:
        """
        Grant exclusive access to device using EVIOCGRAB ioctl.
        Prevents other processes from receiving events from this device.
        
        Raises:
        - EvdevError: If grab fails (device already grabbed, insufficient permissions)
        """
    
    def ungrab(self) -> None:
        """
        Release exclusive access to device.
        Allows other processes to receive events again.
        """
    
    def grab_context(self):
        """
        Context manager for device grabbing.
        Automatically releases grab when exiting context.
        
        Usage:
        with device.grab_context():
            # Device is exclusively grabbed
            for event in device.read_loop():
                process_event(event)
        # Device is automatically ungrabbed
        """

LED and Output Control

Methods for controlling device LEDs and output features.

class InputDevice:
    def leds(self, verbose: bool = False) -> List:
        """
        Return currently active LED keys.
        
        Parameters:
        - verbose: Return human-readable names instead of numeric codes
        
        Returns:
        List of active LED codes/names
        """
    
    def set_led(self, led_num: int, value: int) -> None:
        """
        Set LED state on device.
        
        Parameters:
        - led_num: LED code (from ecodes.LED_*)
        - value: LED state (0=off, 1=on)
        """
    
    def active_keys(self, verbose: bool = False) -> List:
        """
        Return currently pressed/active keys.
        
        Parameters:
        - verbose: Return human-readable names instead of numeric codes
        
        Returns:
        List of active key codes/names
        """

Absolute Axis Control

Methods for working with absolute positioning devices (touchscreens, joysticks).

class InputDevice:
    def absinfo(self, axis_num: int) -> AbsInfo:
        """
        Return AbsInfo for specified absolute axis.
        
        Parameters:
        - axis_num: Absolute axis code (from ecodes.ABS_*)
        
        Returns:
        AbsInfo namedtuple with axis information
        """
    
    def set_absinfo(self, axis_num: int, value=None, min=None, max=None, fuzz=None, flat=None, resolution=None) -> None:
        """
        Update AbsInfo values for absolute axis.
        
        Parameters:
        - axis_num: Absolute axis code (from ecodes.ABS_*)
        - value: Current value (optional)
        - min: Minimum value (optional)  
        - max: Maximum value (optional)
        - fuzz: Fuzz value for noise filtering (optional)
        - flat: Flat value for center deadband (optional)
        - resolution: Resolution in units per mm/radian (optional)
        """

Keyboard Repeat Control

Methods for controlling keyboard repeat rate settings.

class InputDevice:
    @property
    def repeat(self) -> KbdInfo:
        """
        Get keyboard repeat rate information.
        
        Returns:
        KbdInfo namedtuple with delay and repeat rate
        """
    
    @repeat.setter
    def repeat(self, value: KbdInfo) -> None:
        """
        Set keyboard repeat rate.
        
        Parameters:
        - value: KbdInfo with new delay and repeat values
        """

Event Writing

Methods for injecting events into devices (feedback events).

class InputDevice:
    def write_event(self, event: InputEvent) -> None:
        """
        Inject InputEvent into device.
        
        Parameters:
        - event: InputEvent to write to device
        """
    
    def write(self, etype: int, code: int, value: int) -> None:
        """
        Inject input event into device.
        
        Parameters:
        - etype: Event type (from ecodes.EV_*)
        - code: Event code 
        - value: Event value
        """
    
    def syn(self) -> None:
        """Inject SYN_REPORT event to synchronize event stream."""

Force Feedback Control

Methods for managing force feedback effects on compatible devices.

class InputDevice:
    def upload_effect(self, effect: "ff.Effect") -> int:
        """
        Upload force feedback effect to device.
        
        Parameters:
        - effect: Force feedback Effect structure
        
        Returns:
        Effect ID for managing the uploaded effect
        """
    
    def erase_effect(self, ff_id: int) -> None:
        """
        Remove force feedback effect from device.
        
        Parameters:
        - ff_id: Effect ID returned from upload_effect()
        """

Usage Examples

Basic Device Reading

from evdev import InputDevice, list_devices

# Find all input devices
devices = list_devices()
print("Available devices:")
for device_path in devices:
    device = InputDevice(device_path)
    print(f"  {device.path}: {device.name}")
    device.close()

# Monitor specific device
device = InputDevice('/dev/input/event0')
print(f"Monitoring {device.name}")

try:
    for event in device.read_loop():
        print(f"Event: type={event.type}, code={event.code}, value={event.value}")
finally:
    device.close()

Device Capabilities

from evdev import InputDevice, ecodes

device = InputDevice('/dev/input/event0')

# Get raw capabilities
caps = device.capabilities()
print("Device capabilities:", caps)

# Get human-readable capabilities
caps_verbose = device.capabilities(verbose=True)
print("Human-readable capabilities:", caps_verbose)

# Check for specific capabilities
if ecodes.EV_KEY in caps:
    print("Device supports key events")
    key_codes = caps[ecodes.EV_KEY]
    print(f"Supported keys: {len(key_codes)} keys")

device.close()

Exclusive Device Access

from evdev import InputDevice

device = InputDevice('/dev/input/event0')

# Method 1: Manual grab/ungrab
device.grab()
try:
    # Process events exclusively
    for event in device.read():
        process_event(event)
finally:
    device.ungrab()
    device.close()

# Method 2: Context manager (recommended)
with device.grab_context():
    for event in device.read_loop():
        process_event(event)
        if should_stop():
            break

Install with Tessl CLI

npx tessl i tessl/pypi-evdev

docs

device-operations.md

event-codes.md

event-processing.md

force-feedback.md

index.md

virtual-devices.md

tile.json