API¶
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.
- 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
InputEventinstance.
- class evdev.events.RelEvent(event)[source]¶
A relative axis event (e.g moving the mouse 5 units to the left).
- event¶
Reference to an
InputEventinstance.
- class evdev.events.SynEvent(event)[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¶
Reference to an
InputEventinstance.
- class evdev.events.AbsEvent(event)[source]¶
An absolute axis event (e.g the coordinates of a tap on a touchscreen).
- event¶
Reference to an
InputEventinstance.
- 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
InputEventsub-classes. Used byevdev.util.categorize()
eventio¶
- class evdev.eventio.EventIO[source]¶
Base class for reading and writing input events.
This class is used by
InputDeviceandUInput.On,
InputDeviceit used for reading user-generated events (e.g. key presses, mouse movements) and writing feedback events (e.g. leds, beeps).On,
UInputit 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()andasyncore.file_dispatcher.- Return type:
- read_loop()[source]¶
Enter an endless
select.select()loop that yields input events.- Return type:
- read_one()[source]¶
Read and return a single input event as an instance of
InputEvent.Return
Noneif there are no pending input events.- Return type:
- read()[source]¶
Read multiple input events from device. Return a generator object that yields
InputEventinstances. Raises BlockingIOError if there are no available events at the moment.- Return type:
- need_write()[source]¶
Decorator that raises
EvdevErrorif there is no write access to the input device.- Return type:
- 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 aneventattribute (KeyEvent,RelEventetc).
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:
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
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.- Return type:
- async_read()[source]¶
Asyncio coroutine to read multiple input events from device. Return a generator object that yields
InputEventinstances.- Return type:
device¶
- class evdev.device.AbsInfo(value, min, max, fuzz, flat, resolution)[source]¶
Absolute axis information.
A
namedtuplewith absolute axis information - corresponds to theinput_absinfostruct:- 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(delay, repeat)[source]¶
Keyboard repeat rate.
- delay¶
Amount of time that a key must be depressed before it will start to repeat (in milliseconds).
- repeat¶
Keyboard repeat rate in characters per second.
- class evdev.device.DeviceInfo(bustype, vendor, product, version)[source]¶
- bustype¶
- vendor¶
- product¶
- version¶
- class evdev.device.InputDevice(dev, readonly=False)[source]¶
A linux input device from which input events can be read.
- path¶
Path to input device.
- fd¶
A non-blocking file descriptor to the device file.
- info¶
A
DeviceInfoinstance.
- name¶
The name of the event device.
- phys¶
The physical topology of the device.
- uniq¶
The unique identifier 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.
- Overloads:
self, verbose (Literal[False]), absinfo (bool) → dict[int, list[int]]
self, verbose (Literal[True]), absinfo (bool) → dict[tuple[str, int], list[tuple[str, int]]]
Example
>>> device.capabilities() { 1: [272, 273, 274], 2: [0, 1, 6, 8] }
If
verboseisTrue, 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
absinfoisTrue, the list of capabilities will also include absolute axis information in the form ofAbsInfoinstances:{ 3: [ (0, AbsInfo(min=0, max=255, fuzz=0, flat=0)), (1, AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}
Combined with
verbosethe 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
verboseisTrue, 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
verboseisTrue, 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)
- 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 aEVIOCGRABon 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, writeback_id=True)[source]¶
Upload a force feedback effect to a force feedback device and return its effect id. If
writeback_idisTrue, the effect id is written back to theeffectstruct.- Return type:
- 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=False)[source]¶
Return currently active keys.
Example
>>> device.active_keys() [1, 42]
If
verboseisTrue, key codes are resolved to their verbose names. Unknown codes are resolved to'?'. For example:[('KEY_ESC', 1), ('KEY_LEFTSHIFT', 42)]
- absinfo(axis_num)[source]¶
Return current
AbsInfofor input device axis- Parameters:
axis_num (
int) – EV_ABS keycode (exampleecodes.ABS_X)
Example
>>> device.absinfo(ecodes.ABS_X) AbsInfo(value=1501, min=-32768, max=32767, fuzz=0, flat=128, resolution=0)
- set_absinfo(axis_num, value=None, min=None, max=None, fuzz=None, flat=None, resolution=None)[source]¶
Update
AbsInfovalues. Only specified values will be overwritten.- Parameters:
axis_num (
int) – EV_ABS keycode (exampleecodes.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, max_effects=96)[source]¶
A userland input device and that can inject input events into the linux input subsystem.
- classmethod from_device(*devices, filtered_types=(0, 21), **kwargs)[source]¶
Create an UInput device with the capabilities of one or more input devices.
- Parameters:
devices (
InputDevice|str|bytes|PathLike) – Varargs of InputDevice instances or paths to input devices.filtered_types (
tuple[int], default:(0, 21)) – Event types to exclude from the capabilities of the uinput device.**kwargs – Keyword arguments to UInput constructor (i.e. name, vendor etc.).
- Return type:
- __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, max_effects=96)[source]¶
- Parameters:
events (
dict[int,Sequence[int]] |None, default:None) – 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. An event type mapped to an empty sequence enables the event type without enabling any event codes, which is useful for types such asEV_REP.name (
str, default:'py-evdev-uinput') – The name of the input device.vendor (
int, default:1) – Vendor identifier.product (
int, default:1) – Product identifier.version (
int, default:1) – Version identifier.bustype (
int, default:3) – Bustype identifier.phys (
str, default:'py-evdev-uinput') – Physical path.input_props (
Sequence[int] |None, default:None) – Input properties and quirks.max_effects (
int, default:96) – Maximum simultaneous force-feedback effects.
Note
If you do not specify any events, the uinput device will be able to inject only
KEY_*andBTN_*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¶
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
InputDeviceinstance for the fake input device.Noneif the device cannot be opened for reading and writing.
- capabilities(verbose=False, absinfo=True)[source]¶
See
capabilities.
util¶
- evdev.util.list_devices(input_device_dir='/dev/input', writable=True)[source]¶
List readable (and optionally writable) character devices in
input_device_dir.
- evdev.util.is_device(fn, writable=True)[source]¶
Check if
fnis a readable (and optionally writable) character device.- Return type:
- evdev.util.categorize(event)[source]¶
Categorize an event according to its type.
The
event_factorydictionary maps event types to sub-classes ofInputEvent. If the event cannot be categorized, it is returned unmodified.- Return type:
InputEvent|KeyEvent|RelEvent|AbsEvent|SynEvent
- 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 (default:
'?') – 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
typecodemapcontains absolute axis info (instances ofAbsInfo) 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: dict[int, str | tuple[str]] = {0: "KEY_RESERVED", 1: "KEY_ESC", 2: "KEY_1", ...}¶
Keys are a combination of all
BTNandKEYcodes.
- evdev.ecodes.bytype: dict[int, dict[int, str | tuple[str]]] = {0: {0: "SYN_REPORT", 1: "SYN_CONFIG", 2: "SYN_MT_REPORT", 3: "SYN_DROPPED"}, ...}¶
Mapping of event types to other value/name mappings.