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)

A generic input event.

code
sec
timestamp()

Return event timestamp as a float.

type
usec
value
class evdev.events.KeyEvent(event)

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

event
key_down = 1
key_hold = 2
key_up = 0
keycode
keystate
scancode
class evdev.events.AbsEvent(event)

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

event
class evdev.events.RelEvent(event)

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

event
class evdev.events.SynEvent(event)

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

eventio

class evdev.eventio.EventIO

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).
__weakref__

list of weak references to the object (if defined)

fileno()

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

need_write(func)

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

read()

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.

read_loop()

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

read_one()

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

Return None if there are no pending input events.

write(etype, code, value)

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
write_event(event)

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)

eventio_async

class evdev.eventio_async.EventIO
async_read()

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

async_read_loop()

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

async_read_one()

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

device

class evdev.device.InputDevice(dev)

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

__eq__(other)

Two devices are equal if their info attributes are equal.

__hash__ = None
__init__(dev)
Parameters:dev (str) – Path to input device
active_keys(verbose=False)

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)]
capabilities(verbose=False, absinfo=True)

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)) ]}
close()
erase_effect(ff_id)

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

fd
ff_effects_count
fn
grab()

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.

info
leds(verbose=False)

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)]
name
phys
repeat

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

set_led(led_num, value)

Set the state of the selected LED.

Example

>>> device.set_led(ecodes.LED_NUML, 1)
ungrab()

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

Warning

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

upload_effect(effect)

Upload a force feedback effect to a force feedback device.

version
class evdev.device.DeviceInfo
bustype
vendor
product
version
class evdev.device.AbsInfo

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

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).

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')

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

__init__(events=None, name='py-evdev-uinput', vendor=1, product=1, version=1, bustype=3, devnode='/dev/uinput', phys='py-evdev-uinput')
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.

Note

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

capabilities(verbose=False, absinfo=True)

See capabilities.

classmethod from_device(*devices, **kwargs)

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.
  • **kwargs

    Keyword arguments to UInput constructor (i.e. name, vendor etc.).

syn()

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.

util

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

List readable character devices in input_device_dir.

evdev.util.is_device(fn)

Check if fn is a readable and writable character device.

evdev.util.categorize(event)

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='?')

Resolve event codes and types to their verbose names.

Example

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

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

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', ...}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
evdev.ecodes.ecodes {'KEY_END': 107, 'FF_RUMBLE': 80, 'KEY_KPDOT': 83, 'KEY_CNT': 768, ...}'

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
evdev.ecodes.bytype {0: {0: 'SYN_REPORT', 1: 'SYN_CONFIG', 2: 'SYN_MT_REPORT', 3: 'SYN_DROPPED'}, ...}

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)