API Reference

events

This module provides the InputEvent class, which closely resembles the input_event struct defined in linux/input.h:

struct input_event {
    struct timeval time;
    __u16 type;
    __u16 code;
    __s32 value;
};

This module also defines several InputEvent sub-classes that know more about the different types of events (key, abs, rel etc). The event_factory dictionary maps event types to these classes.

Assuming you use the evdev.util.categorize() function to categorize events according to their type, adding or replacing a class for a specific event type becomes a matter of modifying event_factory.

All classes in this module have reasonable str() and repr() methods:

>>> print(event)
event at 1337197425.477827, code 04, type 04, val 458792
>>> print(repr(event))
InputEvent(1337197425L, 477827L, 4, 4, 458792L)

>>> print(key_event)
key event at 1337197425.477835, 28 (KEY_ENTER), up
>>> print(repr(key_event))
KeyEvent(InputEvent(1337197425L, 477835L, 1, 28, 0L))
class evdev.events.InputEvent(sec, usec, type, code, value)[source]

A generic input event.

sec: int

Time in seconds since epoch at which event occurred.

usec: int

Microsecond portion of the timestamp.

type: int

Event type - one of ecodes.EV_*.

code: int

Event code related to the event type.

value: int

Event value related to the event type.

timestamp() float[source]

Return event timestamp as a float.

class evdev.events.KeyEvent(event: InputEvent, allow_unknown: bool = False)[source]

An event generated by a keyboard, button or other key-like devices.

key_up: Final[int] = 0
key_down: Final[int] = 1
key_hold: Final[int] = 2
scancode: int
keystate
keycode
event: InputEvent

Reference to an InputEvent instance.

class evdev.events.RelEvent(event: InputEvent)[source]

A relative axis event (e.g moving the mouse 5 units to the left).

event: InputEvent

Reference to an InputEvent instance.

class evdev.events.SynEvent(event: InputEvent)[source]

A synchronization event. Used as markers to separate events. Events may be separated in time or in space, such as with the multitouch protocol.

event: InputEvent

Reference to an InputEvent instance.

class evdev.events.AbsEvent(event: InputEvent)[source]

An absolute axis event (e.g the coordinates of a tap on a touchscreen).

event: InputEvent

Reference to an InputEvent instance.

evdev.events.event_factory = {0: <class 'evdev.events.SynEvent'>, 1: <class 'evdev.events.KeyEvent'>, 2: <class 'evdev.events.RelEvent'>, 3: <class 'evdev.events.AbsEvent'>}

A mapping of event types to InputEvent sub-classes. Used by evdev.util.categorize()

eventio

class evdev.eventio.EventIO[source]

Base class for reading and writing input events.

This class is used by InputDevice and UInput.

  • On, InputDevice it used for reading user-generated events (e.g. key presses, mouse movements) and writing feedback events (e.g. leds, beeps).

  • On, UInput it used for writing user-generated events (e.g. key presses, mouse movements) and reading feedback events (e.g. leds, beeps).

fileno()[source]

Return the file descriptor to the open event device. This makes it possible to pass instances directly to select.select() and asyncore.file_dispatcher.

read_loop() Iterator[InputEvent][source]

Enter an endless select.select() loop that yields input events.

read_one() InputEvent | None[source]

Read and return a single input event as an instance of InputEvent.

Return None if there are no pending input events.

read() Iterator[InputEvent][source]

Read multiple input events from device. Return a generator object that yields InputEvent instances. Raises BlockingIOError if there are no available events at the moment.

need_write()[source]

Decorator that raises EvdevError if there is no write access to the input device.

write_event(event)[source]

Inject an input event into the input subsystem. Events are queued until a synchronization event is received.

Parameters:

event (InputEvent) – InputEvent instance or an object with an event attribute (KeyEvent, RelEvent etc).

Example

>>> ev = InputEvent(1334414993, 274296, ecodes.EV_KEY, ecodes.KEY_A, 1)
>>> ui.write_event(ev)
write(etype: int, code: int, value: int)[source]

Inject an input event into the input subsystem. Events are queued until a synchronization event is received.

Parameters:
  • etype – event type (e.g. EV_KEY).

  • code – event code (e.g. KEY_A).

  • value – event value (e.g. 0 1 2 - depends on event type).

Example

>>> ui.write(e.EV_KEY, e.KEY_A, 1) # key A - down
>>> ui.write(e.EV_KEY, e.KEY_A, 0) # key A - up
syn()[source]

Inject a SYN_REPORT event into the input subsystem. Events queued by write() will be fired. If possible, events will be merged into an ‘atomic’ event.

close()[source]
__firstlineno__ = 16
__static_attributes__ = ()
__weakref__

list of weak references to the object

eventio_async

class evdev.eventio_async.EventIO[source]
async_read_one()[source]

Asyncio coroutine to read and return a single input event as an instance of InputEvent.

async_read()[source]

Asyncio coroutine to read multiple input events from device. Return a generator object that yields InputEvent instances.

async_read_loop()[source]

Return an iterator that yields input events. This iterator is compatible with the async for syntax.

close()[source]
__annotations__ = {}
__firstlineno__ = 10
__static_attributes__ = ()

device

class evdev.device.AbsInfo(value: int, min: int, max: int, fuzz: int, flat: int, resolution: int)[source]

Absolute axis information.

A namedtuple with absolute axis information - corresponds to the input_absinfo struct:

value

Latest reported value for the axis.

Type:

int

min

Specifies minimum value for the axis.

Type:

int

max

Specifies maximum value for the axis.

Type:

int

fuzz

Specifies fuzz value that is used to filter noise from the event stream.

Type:

int

flat

Values that are within this value will be discarded by joydev interface and reported as 0 instead.

Type:

int

resolution

Specifies resolution for the values reported for the axis. Resolution for main axes (ABS_X, ABS_Y, ABS_Z) is reported in units per millimeter (units/mm), resolution for rotational axes (ABS_RX, ABS_RY, ABS_RZ) is reported in units per radian.

Type:

int

Note

The input core does not clamp reported values to the [minimum, maximum] limits, such task is left to userspace.

value: int

Alias for field number 0

min: int

Alias for field number 1

max: int

Alias for field number 2

fuzz: int

Alias for field number 3

flat: int

Alias for field number 4

resolution: int

Alias for field number 5

__annotations__ = {'flat': <class 'int'>, 'fuzz': <class 'int'>, 'max': <class 'int'>, 'min': <class 'int'>, 'resolution': <class 'int'>, 'value': <class 'int'>}
__firstlineno__ = 13
__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__match_args__ = ('value', 'min', 'max', 'fuzz', 'flat', 'resolution')
static __new__(_cls, value: int, min: int, max: int, fuzz: int, flat: int, resolution: int)

Create new instance of AbsInfo(value, min, max, fuzz, flat, resolution)

__orig_bases__ = (<function NamedTuple>,)
__replace__(**kwds)

Return a new AbsInfo object replacing specified fields with new values

__static_attributes__ = ()
class evdev.device.KbdInfo(delay: int, repeat: int)[source]

Keyboard repeat rate.

delay

Amount of time that a key must be depressed before it will start to repeat (in milliseconds).

Type:

int

repeat

Keyboard repeat rate in characters per second.

Type:

int

delay: int

Alias for field number 0

repeat: int

Alias for field number 1

__annotations__ = {'delay': <class 'int'>, 'repeat': <class 'int'>}
__firstlineno__ = 63
__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__match_args__ = ('delay', 'repeat')
static __new__(_cls, delay: int, repeat: int)

Create new instance of KbdInfo(delay, repeat)

__orig_bases__ = (<function NamedTuple>,)
__replace__(**kwds)

Return a new KbdInfo object replacing specified fields with new values

__static_attributes__ = ()
class evdev.device.DeviceInfo(bustype: int, vendor: int, product: int, version: int)[source]
bustype
Type:

int

vendor
Type:

int

product
Type:

int

version
Type:

int

bustype: int

Alias for field number 0

vendor: int

Alias for field number 1

product: int

Alias for field number 2

version: int

Alias for field number 3

__annotations__ = {'bustype': <class 'int'>, 'product': <class 'int'>, 'vendor': <class 'int'>, 'version': <class 'int'>}
__firstlineno__ = 83
__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__match_args__ = ('bustype', 'vendor', 'product', 'version')
static __new__(_cls, bustype: int, vendor: int, product: int, version: int)

Create new instance of DeviceInfo(bustype, vendor, product, version)

__orig_bases__ = (<function NamedTuple>,)
__replace__(**kwds)

Return a new DeviceInfo object replacing specified fields with new values

__static_attributes__ = ()
class evdev.device.InputDevice(dev: str | bytes | PathLike)[source]

A linux input device from which input events can be read.

__init__(dev: str | bytes | PathLike)[source]
Parameters:

dev (str|bytes|PathLike) – Path to input device

path

Path to input device.

fd: int

A non-blocking file descriptor to the device file.

info

A DeviceInfo instance.

name: str

The name of the event device.

phys: str

The physical topology of the device.

uniq: str

The unique identifier of the device.

version: int

The evdev protocol version.

ff_effects_count

The number of force feedback effects the device can keep in its memory.

capabilities(verbose: bool = False, absinfo: bool = True)[source]

Return the event types that this device supports as a mapping of supported event types to lists of handled event codes.

Example

>>> device.capabilities()
{ 1: [272, 273, 274],
  2: [0, 1, 6, 8] }

If verbose is True, event codes and types will be resolved to their names.

{ ('EV_KEY', 1): [('BTN_MOUSE', 272),
                  ('BTN_RIGHT', 273),
                  ('BTN_MIDDLE', 273)],
  ('EV_REL', 2): [('REL_X', 0),
                  ('REL_Y', 1),
                  ('REL_HWHEEL', 6),
                  ('REL_WHEEL', 8)] }

Unknown codes or types will be resolved to '?'.

If absinfo is True, the list of capabilities will also include absolute axis information in the form of AbsInfo instances:

{ 3: [ (0, AbsInfo(min=0, max=255, fuzz=0, flat=0)),
       (1, AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}

Combined with verbose the above becomes:

{ ('EV_ABS', 3): [ (('ABS_X', 0), AbsInfo(min=0, max=255, fuzz=0, flat=0)),
                   (('ABS_Y', 1), AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}
input_props(verbose: bool = False)[source]

Get device properties and quirks.

Example

>>> device.input_props()
[0, 5]

If verbose is True, input properties are resolved to their names. Unknown codes are resolved to '?':

[('INPUT_PROP_POINTER', 0), ('INPUT_PROP_POINTING_STICK', 5)]
leds(verbose: bool = False)[source]

Return currently set LED keys.

Example

>>> device.leds()
[0, 1, 8, 9]

If verbose is True, event codes are resolved to their names. Unknown codes are resolved to '?':

[('LED_NUML', 0), ('LED_CAPSL', 1), ('LED_MISC', 8), ('LED_MAIL', 9)]
set_led(led_num: int, value: int)[source]

Set the state of the selected LED.

Example

>>> device.set_led(ecodes.LED_NUML, 1)
__eq__(other)[source]

Two devices are equal if their info attributes are equal.

__fspath__()[source]
close()[source]
grab()[source]

Grab input device using EVIOCGRAB - other applications will be unable to receive events until the device is released. Only one process can hold a EVIOCGRAB on a device.

Warning

Grabbing an already grabbed device will raise an OSError.

ungrab()[source]

Release device if it has been already grabbed (uses EVIOCGRAB).

Warning

Releasing an already released device will raise an OSError('Invalid argument').

grab_context()[source]

A context manager for the duration of which only the current process will be able to receive events from the device.

upload_effect(effect: ff.Effect)[source]

Upload a force feedback effect to a force feedback device.

erase_effect(ff_id)[source]

Erase a force effect from a force feedback device. This also stops the effect.

property repeat

Get or set the keyboard repeat rate (in characters per minute) and delay (in milliseconds).

active_keys(verbose: bool = False)[source]

Return currently active keys.

Example

>>> device.active_keys()
[1, 42]

If verbose is True, key codes are resolved to their verbose names. Unknown codes are resolved to '?'. For example:

[('KEY_ESC', 1), ('KEY_LEFTSHIFT', 42)]
absinfo(axis_num: int)[source]

Return current AbsInfo for input device axis

Parameters:

axis_num (int) – EV_ABS keycode (example ecodes.ABS_X)

Example

>>> device.absinfo(ecodes.ABS_X)
AbsInfo(value=1501, min=-32768, max=32767, fuzz=0, flat=128, resolution=0)
__annotations__ = {'fd': 'int', 'name': 'str', 'phys': 'str', 'uniq': 'str', 'version': 'int'}
__firstlineno__ = 103
__hash__ = None
__static_attributes__ = ('_rawcapabilities', 'fd', 'ff_effects_count', 'info', 'name', 'path', 'phys', 'uniq', 'version')
set_absinfo(axis_num: int, value=None, min=None, max=None, fuzz=None, flat=None, resolution=None)[source]

Update AbsInfo values. Only specified values will be overwritten.

Parameters:

axis_num (int) – EV_ABS keycode (example ecodes.ABS_X)

Example

>>> device.set_absinfo(ecodes.ABS_X, min=-2000, max=2000)

You can also unpack AbsInfo tuple that will overwrite all values

>>> device.set_absinfo(ecodes.ABS_Y, *AbsInfo(0, -2000, 2000, 0, 15, 0))

uinput

class evdev.uinput.UInput(events: Dict[int, Sequence[int]] | None = None, name: str = 'py-evdev-uinput', vendor: int = 1, product: int = 1, version: int = 1, bustype: int = 3, devnode: str = '/dev/uinput', phys: str = 'py-evdev-uinput', input_props=None, max_effects=96)[source]

A userland input device and that can inject input events into the linux input subsystem.

classmethod from_device(*devices: InputDevice | str | bytes | PathLike, filtered_types: Tuple[int] = (0, 21), **kwargs)[source]

Create an UInput device with the capabilities of one or more input devices.

Parameters:
  • devices (InputDevice|str) – Varargs of InputDevice instances or paths to input devices.

  • filtered_types (Tuple[event type codes]) – Event types to exclude from the capabilities of the uinput device.

  • **kwargs – Keyword arguments to UInput constructor (i.e. name, vendor etc.).

__init__(events: Dict[int, Sequence[int]] | None = None, name: str = 'py-evdev-uinput', vendor: int = 1, product: int = 1, version: int = 1, bustype: int = 3, devnode: str = '/dev/uinput', phys: str = 'py-evdev-uinput', input_props=None, max_effects=96)[source]
Parameters:
  • events (dict) – Dictionary of event types mapping to lists of event codes. The event types and codes that the uinput device will be able to inject - defaults to all key codes.

  • name – The name of the input device.

  • vendor – Vendor identifier.

  • product – Product identifier.

  • version – Version identifier.

  • bustype – Bustype identifier.

  • phys – Physical path.

  • input_props – Input properties and quirks.

  • max_effects – Maximum simultaneous force-feedback effects.

Note

If you do not specify any events, the uinput device will be able to inject only KEY_* and BTN_* event codes.

name: str

Uinput device name.

vendor: int

Device vendor identifier.

product: int

Device product identifier.

version: int

Device version identifier.

bustype: int

Device bustype - e.g. BUS_USB.

phys: str

Uinput device physical path.

devnode: str

Uinput device node - e.g. /dev/uinput/.

fd

Write-only, non-blocking file descriptor to the uinput device node.

device: InputDevice

An InputDevice instance for the fake input device. None if the device cannot be opened for reading and writing.

capabilities(verbose: bool = False, absinfo: bool = True)[source]

See capabilities.

util

evdev.util.list_devices(input_device_dir: str | bytes | PathLike = '/dev/input') List[str][source]

List readable character devices in input_device_dir.

evdev.util.is_device(fn: str | bytes | PathLike) bool[source]

Check if fn is a readable and writable character device.

evdev.util.categorize(event)[source]

Categorize an event according to its type.

The event_factory dictionary maps event types to sub-classes of InputEvent. If the event cannot be categorized, it is returned unmodified.

evdev.util.resolve_ecodes(ecode_dict, ecode_list, unknown='?')[source]

Resolve event codes and types to their verbose names.

Example

>>> resolve_ecodes(ecodes.BTN, [272, 273, 274])
[(['BTN_LEFT', 'BTN_MOUSE'], 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 274)]
evdev.util.resolve_ecodes_dict(typecodemap, unknown='?')[source]

Resolve event codes and types to their verbose names.

Parameters:
  • typecodemap – mapping of event types to lists of event codes.

  • unknown – symbol to which unknown types or codes will be resolved.

Example

>>> resolve_ecodes_dict({ 1: [272, 273, 274] })
{ ('EV_KEY', 1): [('BTN_MOUSE',  272),
                  ('BTN_RIGHT',  273),
                  ('BTN_MIDDLE', 274)] }

If typecodemap contains absolute axis info (instances of AbsInfo ) the result would look like:

>>> resolve_ecodes_dict({ 3: [(0, AbsInfo(...))] })
{ ('EV_ABS', 3L): [(('ABS_X', 0L), AbsInfo(...))] }

ecodes

This modules exposes the integer constants defined in linux/input.h and linux/input-event-codes.h.

Exposed constants:

KEY, ABS, REL, SW, MSC, LED, BTN, REP, SND, ID, EV,
BUS, SYN, FF, FF_STATUS, INPUT_PROP

This module also provides reverse and forward mappings of the names and values of the above mentioned constants:

>>> evdev.ecodes.KEY_A
30

>>> evdev.ecodes.ecodes['KEY_A']
30

>>> evdev.ecodes.KEY[30]
'KEY_A'

>>> evdev.ecodes.REL[0]
'REL_X'

>>> evdev.ecodes.EV[evdev.ecodes.EV_KEY]
'EV_KEY'

>>> evdev.ecodes.bytype[evdev.ecodes.EV_REL][0]
'REL_X'

Keep in mind that values in reverse mappings may point to one or more event codes. For example:

>>> evdev.ecodes.FF[80]
('FF_EFFECT_MIN', 'FF_RUMBLE')

>>> evdev.ecodes.FF[81]
'FF_PERIODIC'
evdev.ecodes.keys {0: 'KEY_RESERVED', 1: 'KEY_ESC', 2: 'KEY_1', ...}

Keys are a combination of all BTN and KEY codes.

evdev.ecodes.ecodes {'KEY_END': 107, 'FF_RUMBLE': 80, 'KEY_KPDOT': 83, 'KEY_CNT': 768, ...}'

Mapping of names to values.

evdev.ecodes.bytype {0: {0: 'SYN_REPORT', 1: 'SYN_CONFIG', 2: 'SYN_MT_REPORT', 3: 'SYN_DROPPED'}, ...}

Mapping of event types to other value/name mappings.