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

Time in seconds since epoch at which event occurred.

usec

Microsecond portion of the timestamp.

type

Event type - one of ecodes.EV_*.

code

Event code related to the event type.

value

Event value related to the event type.

timestamp()[source]

Return event timestamp as a float.

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

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

key_up = 0
key_down = 1
key_hold = 2
scancode
keystate
keycode
event

Reference to an InputEvent instance.

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

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

event

Reference to an InputEvent instance.

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

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

event

Reference to an InputEvent instance.

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

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

event

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()[source]

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

read_one()[source]

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

Return None if there are no pending input events.

read()[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, code, value)[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
close()[source]
__weakref__

list of weak references to the object (if defined)

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]

device

class evdev.device.AbsInfo[source]

Absolute axis information.

A namedtuple used for storing absolute axis information - corresponds to the input_absinfo struct:

value

Latest reported value for the axis.

min

Specifies minimum value for the axis.

max

Specifies maximum value for the axis.

fuzz

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

flat

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

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.

Note

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

class evdev.device.KbdInfo[source]

Keyboard repeat rate.

repeat

Keyboard repeat rate in characters per second.

delay

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

class evdev.device.DeviceInfo[source]
bustype
vendor
product
version
class evdev.device.InputDevice(dev)[source]

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

__init__(dev)[source]
Parameters:dev (str|bytes|PathLike) – Path to input device
path

Path to input device.

fd

A non-blocking file descriptor to the device file.

info

A DeviceInfo instance.

name

The name of the event device.

phys

The physical topology of the device.

uniq

The unique address of the device.

version

The evdev protocol version.

ff_effects_count

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

capabilities(verbose=False, absinfo=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=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=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, value)[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.

__ne__(other)[source]

Return self!=value.

__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 IOError.

ungrab()[source]

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

Warning

Releasing an already released device will raise an IOError('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)[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.

repeat

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

active_keys(verbose=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)]
fn
absinfo(axis_num)[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)
__hash__ = None
set_absinfo(axis_num, 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=None, name='py-evdev-uinput', vendor=1, product=1, version=1, bustype=3, devnode='/dev/uinput', phys='py-evdev-uinput', input_props=None)[source]

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

classmethod from_device(*devices, **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=None, name='py-evdev-uinput', vendor=1, product=1, version=1, bustype=3, devnode='/dev/uinput', phys='py-evdev-uinput', input_props=None)[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.

Note

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

name

Uinput device name.

vendor

Device vendor identifier.

product

Device product identifier.

version

Device version identifier.

bustype

Device bustype - e.g. BUS_USB.

phys = None

Uinput device physical path.

devnode

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

fd

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

device

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

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.

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

See capabilities.

util

evdev.util.list_devices(input_device_dir='/dev/input')[source]

List readable character devices in input_device_dir.

evdev.util.is_device(fn)[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_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(...))] }
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)]

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.