# libevdev package

## Submodules

## libevdev.const module

class `EvdevBit`

  Bases: `object`

  Base class representing an evdev bit, comprised of a name and a value. These two properties are guaranteed to exist on anything describing an event code, event type or input property that comes out of libevdev:

      >>> print(libevdev.EV_ABS.name)
      EV_ABS
      >>> print(libevdev.EV_ABS.value)
      3
      >>> print(libevdev.EV_SYN.SYN_REPORT.name)
      SYN_REPORT
      >>> print(libevdev.EV_SYN.SYN_REPORT.value)
      0
      >>> print(libevdev.INPUT_PROP_DIRECT.name)
      INPUT_PROP_DIRECT
      >>> print(libevdev.INPUT_PROP_DIRECT.value)
      1

  `value`

    The numeric value of the event code

  `name`

    The string name of this event code

class `EventCode`

  Bases: `libevdev.const.EvdevBit`

  Warning

  Do not instantiate an object of this class, all objects you’ll ever need are already present in the libevdev namespace. Use `evbit()` to get an `EventCode` from numerical or string values.

  A class representing an evdev event code, e.g. libevdev.EV_ABS.ABS_X. To use a `EventCode`, use the namespaced name directly:

      >>> print(libevdev.EV_ABS.ABS_X)
      ABS_X:0
      >>> print(libevdev.EV_ABS.ABS_Y)
      ABS_X:1
      >>> code = libevdev.EV_REL.REL_X
      >>> print(code.type)
      EV_REL:2

  `value`

    The numeric value of the event code

  `name`

    The string name of this event code. Where the name is not defined, a fake name is generated by this module, consisting of the prefix and the uppercase hexadecimal value, e.g. `REL_0B`. These generated names (see `EventCode.is_defined()`) should never be used as input.

    Note that even defined names are not a stable API. From time to time the kernel introduces a new name and aliases the old one. The same numeric event code may then return a different name than before. This does not affect the `evbit()` function which continues to return the correct event code.

  `type`

    The `EventType` for this event code

  `is_defined`

    `True` if this event bit has a `#define` in the kernel header. `EventCode` objects not defined in the header have a name composed of the type name plus the hex code, e.g. `KEY_2E8`.

    Usually you will not need to check this property unless you need to filter for known codes only.

class `EventType`

  Bases: `libevdev.const.EvdevBit`

  Warning

  Do not instantiate an object of this class, all objects you’ll ever need are already present in the libevdev namespace. Use `evbit()` to get an `EventType` from numerical or string values.

  A class represending an evdev event type (e.g. EV_ABS). All event codes within this type are available as class constants:

      >>> print(libevdev.EV_ABS)
      EV_ABS:3
      >>> print(libevdev.EV_ABS.ABS_X)
      ABS_X:0
      >>> print(libevdev.EV_ABS.max)
      63
      >>> print(libevdev.EV_ABS.ABS_MAX)
      63
      >>> for code in libevdev.EV_ABS.codes[:3]:
      ...     print(code)
      ...
      ABS_X:0
      ABS_Y:1
      ABS_Z:2

  `value`

    The numeric value of the event type

  `name`

    The string name of this event type

  `codes`

    A list of `EventCode` objects for this type

  `max`

    The maximum event code permitted in this type as integer

class `InputProperty`

  Bases: `libevdev.const.EvdevBit`

  Warning

  Do not instantiate an object of this class, all objects you’ll ever need are already present in the libevdev namespace. Use `propbit()` to get an `InputProperty` from numerical or string values.

  A class representing an evdev input property:

      >>> print(libevdev.INPUT_PROP_DIRECT)
      INPUT_PROP_DIRECT:1

  `value`

    The numeric value of the property

  `name`

    The string name of this property

`evbit`(evtype, evcode=None)

  Takes an event type and an (optional) event code and returns the Enum representing that type or code, whichever applies. For example:

      >>> print(libevdev.evbit(0))
      EV_SYN:0

      >>> print(libevdev.evbit(2))
      EV_REL:2

      >>> print(libevdev.evbit(2, 1))
      REL_Y:1

      >>> print(libevdev.evbit(3, 4))
      ABS_RY:4

      >>> print(libevdev.evbit('EV_ABS'))
      EV_ABS:3

      >>> print(libevdev.evbit('EV_ABS', 'ABS_X'))
      ABS_X:0

  A special case is the lookup of an string-based event code without the type. Where the string identifier is unique, this will return the right value.

      >>> print(libevdev.evbit('ABS_X'))
      ABS_X:0

  The return value can be used in the libevdev API wherever an `EventCode` or `EventType` is expected.

  Notable behavior for invalid types or names:

  - If the type does not exist, this function returns None

  - If the type exists but the event code’s numeric value does not have a symbolic name (and is within the allowed max of the type), this function returns a valid event code

  - If the code is outside the allowed maximum for the given type, this function returns None

  - If the type name exists but the string value is not a code name, this function returns None

  Examples for the above behaviour:

      >>> print(libevdev.evbit(8))
      None
      >>> print(libevdev.evbit('INVALID'))
      None
      >>> print(libevdev.evbit('EV_ABS', 62))
      ABS_3E:62
      >>> print(libevdev.evbit('EV_ABS', 5000))
      None
      >>> print(libevdev.evbit('EV_ABS', 'INVALID'))
      None

  Parameters

    - evtype – the numeric value or string identifying the event type

    - evcode – the numeric value or string identifying the event code

  Returns

    An event code value representing the code

  Return type

    EventCode or EventType

`propbit`(prop)

  Takes a property value and returns the `InputProperty` representing that property:

      >>> print(libevdev.propbit(0))
      INPUT_PROP_POINTER:0
      >>> print(libevdev.propbit('INPUT_PROP_POINTER'))
      INPUT_PROP_POINTER:0
      >>> print(libevdev.propbit(1000))
      None
      >>> print(libevdev.propbit('Invalid'))
      None

  Parameters

    prop – the numeric value or string identifying the property

  Returns

    the converted `InputProperty` or None if it does not exist

  Return type

    InputProperty

## libevdev.device module

class `Device`(fd=None)

  Bases: `object`

  This class represents an evdev device backed by libevdev. The device may represent a real device in the system or a constructed device where the caller supplies all properties of the device.

  If a file is given, the device initializes from that file, otherwise the device is uninitialized and needs to be set up by the caller:

      fd = open("/dev/input/event0", "rb")
      l = libevdev.Device(fd)
      # l now represents the device on event0

      l2 = libevdev.Device()
      l2.name = "test device"
      l2.enable(libevdev.EV_REL.REL_X)
      # l2 is an unbound device with the REL_X bit set

  Note that if a device is constructed manually, the fd of the device is always None.

  Note

  The device is always set to CLOCK_MONOTONIC.

  Parameters

    fd (A file-like object) – fd pointing to a `/dev/input/eventX` event node

  property `absinfo`

    Query the device’s absinfo for the given event code. This attribute can both query and modify the `InputAbsInfo` values of this device:

        >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X]
        >>> print(f'Resolution is {ai.resolution}')
        Resolution is 33
        >>> ai = d.absinfo[libevdev.EV_ABS.ABS_Z]
        >>> print(ai)
        None

    The returned object is a dict-like object that only accepts event codes of type EV_ABS as keys. No other operation than key-based access is supported.

    When used as a setter, the provided `InputAbsInfo` becomes the new absinfo of this axis:

        >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X]
        >>> print(f'Resolution is {ai.resolution}')
        Resolution is 33
        >>> ai.resolution = 45
        >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai
        >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X]
        >>> print(f'Resolution is now {ai.resolution}')
        Resolution is now 45

    When used as a setter, any attribute of `InputAbsInfo` that is `None` is ignored:

        >>> ai = InputAbsInfo(resolution=72)
        >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai
        >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X]
        >>> print(f'Resolution is now {ai.resolution}')
        Resolution is now 72

    Warning

    Setting the absinfo for a non-existing EV_ABS code is invalid. Use `enable()` instead.

    Returns

      an class:InputAbsInfo struct or None if the device does not have the event code

    Raises

      `InvalidArgumentException` when trying to set an axis that is not enabled.

  `create_uinput_device`(uinput_fd=None)

    Creates and returns a new `Device` based on this libevdev device. The new device is equivalent to one created with `libevdev.Device()`, i.e. it is one that does not have a file descriptor associated.

    To create a uinput device from an existing device:

        fd = open('/dev/input/event0', 'rb')
        d = libevdev.Device(fd)
        d.name = 'duplicated device'
        d.create_uinput_device()
        # d is now a duplicate of the event0 device with a custom name
        fd.close()

    Or to create a new device from scratch:

        d = libevdev.Device()
        d.name = 'test device'
        d.enable(libevdev.EV_KEY.BTN_LEFT)
        d.create_uinput_device()
        # d is now a device with a single button

    Parameters

      uinput_fd – A file descriptor to the /dev/input/uinput device. If None, the device is opened and closed automatically.

    Raises

      OSError

  property `current_slot`
    Returns

      the current slot on this device or `None` if this device does not support slots

    Note

      Read-only

  property `devnode`

    Returns the device node for this device. The device node is None if this device has not been created as uinput device.

  `disable`(event_code)

    Disable the given event type or event code on this device. If the device does not support this type or code, this function does nothing. Otherwise, all future events from this device that match this type or code will be discarded:

        >>> d.disable(libevdev.EV_ABS)
        # All EV_ABS events are filtered now
        >>> d.disable(libevdev.EV_KEY.BTN_LEFT)
        # All BTN_LEFt events are filtered now

    To re-enable an event type or code, use `enable()`

    Parameters

      event_code (EventType or EventCode) – the event type or code

  property `driver_version`
    Returns

      the device’s driver version

  `enable`(event_code, data=None)

    Enable an event type or event code on this device, even if not supported by this device. If event_code is an `EventType`, that type is enabled and data is ignored.

    If event_code is one of `libevdev.EV_ABS.ABS_*`, then data must be a `InputAbsInfo`. Any unset fields of the `InputAbsInfo` are replaced with 0, i.e. the following example is valid and results in a fuzz/flat/resolution of zero:

        ctx = libevdev.Device()
        abs = InputAbsInfo(minimum=0, maximum=100)
        ctx.enable(libevdev.EV_ABS.ABS_X, data)

    If event_code is one of `libevdev.EV_REP.REP_`, then data must be an integer.

    If event_code is one of `libevdev.INPUT_PROP_`, then the given input property is enabled.

    Parameters

      - event_code (EventCode or EventType) – the event code

      - data – if event_code is not `None`, data points to the code-specific information.

  property `evbits`

    Returns a dict with all supported event types and event codes, in the form of:

        {
          libevdev.EV_ABS: [libevdev.EV_ABS.ABS_X, ...],
          libevdev.EV_KEY: [libevdev.EV_KEY.BTN_LEFT, ...],
        }

  `events`()

    Returns an iterable with currently pending events.

    Event processing should look like this:

        fd = open("/dev/input/event0", "rb")
        fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)  # optional
        ctx = libevdev.Device(fd)

        while True:
            for e in ctx.events():
                print(e):

            ... other mainloop code ...

    This function detects if the file descriptor is in blocking or non-blocking mode and adjusts its behavior accordingly. If the file descriptor is in nonblocking mode and no events are available, this function returns immediately. If the file descriptor is blocking, this function blocks if there are no events available.

    Returns

      an iterable with the currently pending events

  property `fd`

    This fd represents the file descriptor to this device, if any. If no fd was provided in the constructor, None is returned. If the device was used to create a uinput device, None is returned.

    The fd may only be changed if it was not initially None and then it overwrites the file object provided in the constructor (or a previous call to this function). The new file object becomes the object referencing this device, further events are polled from that file.

    Warning

    A device initialized without a file descriptor may not change its fd.

    Note that libevdev does not synchronize the device and relies on the caller to ensure that the new file object points to the same device as this context. If the underlying device changes, the behavior is undefined.

    Raises

      InvalidFileError - the file is invalid or this device does not allow a file to be set

  `grab`()

    Exclusively grabs the device, preventing events from being seen by anyone else. This includes in-kernel consumers of the events (e.g. for rfkill) and should be used with care.

    A grab is valid until the file descriptor is closed or until `ungrab()` is called, whichever happens earlier. libevdev re-issues the grab on the device after changing the fd. If the original file descriptor is still open when changing the fd on the device, re-issuing the grab will fail silently:

        fd1 = open("/dev/input/event0", "rb")
        d = libevdev.Device(fd1)
        d.grab()
        # device is now exclusively grabbed

        fd1.close()
        fd2 = open("/dev/input/event0", "rb")
        d.fd = fd2
        # device is now exclusively grabbed

        fd3 = open("/dev/input/event0", "rb")
        d.fd = fd3
        # ERROR: fd2 is still open and the grab fails

  `has`(evcode)
    Parameters

      evcode (EventType or EventCode) – the event type or event code

    Returns

      True if the device has the type and/or code, False otherwise

  `has_property`(prop)
    Parameters

      prop – a property

    Returns

      True if the device has the property, False otherwise

  property `id`
    Returns

      A dict with the keys ‘bustype’, ‘vendor’, ‘product’, ‘version’.

    When used as a setter, only existing keys are applied to the device. For example, to update the product ID only:

        ctx = Device()
        id["property"] = 1234
        ctx.id = id

  property `name`
    Returns

      the device name

  property `num_slots`
    Returns

      the number of slots on this device or `None` if this device does not support slots

    Note

      Read-only

  property `phys`
    Returns

      the device’s kernel phys or None.

  property `properties`

    Returns a list of all supported input properties

  `send_events`(events)

    Send the list of `InputEvent` events through this device. All events must have a valid `EventCode` and value, the timestamp in the event is ignored and the kernel fills in its own timestamp.

    This function may only be called on a uinput device, not on a normal device.

    Warning

    an event list must always be terminated with a `libevdev.EV_SYN.SYN_REPORT` event or the kernel may delay processing.

    Parameters

      events – a list of `InputEvent` events

  `set_leds`(leds)

    Write the LEDs to the device:

        >>> fd = open(path, 'r+b', buffering=0)
        >>> d = libevdev.Device(fd)
        >>> d.set_leds([(libevdev.EV_LED.LED_NUML, 0),
                        (libevdev.EV_LED.LED_SCROLLL, 1)])

    Updating LED states require the fd to be in write-mode.

  property `slots`

    Returns a tuple with the available slots, each of which contains a wrapper object to access a slot value:

        >>> d = libevdev.Device(fd)
        >>> print(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X])
        1000
        >>> print(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_Y])
        500
        >>> print(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_X])
        200
        >>> print(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_Y])
        300

    Alternatively, the tuple can be iterated on:

        xcode = libevdev.EV_ABS.ABS_MT_POSITION_X
        ycode = libevdev.EV_ABS.ABS_MT_POSITION_Y

        for s in d.slots:
             position = (s[xcode], s[ycode])

    The only values available for each slot are the ones in the `libevdev.EV_ABS.ABS_MT_*` range (but not `libevdev.EV_ABS.ABS_MT_SLOT`).

  `sync`(force=False)

    Returns an iterator with events pending to re-sync the caller’s view of the device with the one from libevdev.

    Parameters

      force – if set, the device forces an internal sync. This is required after changing the fd of the device when the device state may have changed while libevdev was not processing events.

  `sync_absinfo_to_kernel`(code)

    Synchronizes our view of an absinfo axis to the kernel, thus updating the the device for every other client. This function should be used with care. Not only does it change the kernel device and thus may affect the behavior of other processes but it is racy: any client that has this device node open already may never see the updates.

    To use this function, update the absinfo for the desired axis first:

        >>> fd = open('/dev/input/event0', 'rb')
        >>> d = libevdev.Device(fd)
        >>> ai = InputAbsInfo(resolution=72)
        >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai
        >>> d.sync_absinfo_to_kernel(libevdev.EV_ABS.ABS_X)

  property `syspath`

    Returns the syspath for this device. The syspath is None if this device has not been created as uinput device.

  `ungrab`()

    Removes an exclusive grabs on the device, see `grab()`.

  property `uniq`
    Returns

      the device’s uniq string or None

  property `value`

    Returns the current value for a given event code or None where the event code does not exist on the device:

        >>> d = libevdev.Device(fd)
        >>> print(d.value[libevdev.EV_ABS.ABS_X])
        1024
        >>> print(d.value[libevdev.EV_ABS.ABS_Y])
        512
        >>> print(d.value[libevdev.EV_ABS.ABS_Z])
        None

    The returned object is a dict-like object that only accepts event codes as keys. No other operation than key-based access is supported.

    The default value for all codes is 0. State-less axes like the `EV_REL` range always return 0 for all supported event codes.

exception `DeviceGrabError`

  Bases: `Exception`

  A device grab failed to be issued. A caller must not assume that it has exclusive access to the events on the device.

exception `EventsDroppedException`

  Bases: `Exception`

  Notification that the device has dropped events, raised in response to a EV_SYN SYN_DROPPED event.

  This exception is raised AFTER the EV_SYN, SYN_DROPPED event has been passed on. If SYN_DROPPED events are processed manually, then this exception can be ignored.

  Once received (or in response to a SYN_DROPPED event) a caller should call device.sync() and process the events accordingly (if any).

  Example:

      fd = open("/dev/input/event0", "rb")
      ctx = libevdev.Device(fd)

      while True:
          try:
              for e in ctx.events():
                  print(e):
          except EventsDroppedException:
              print('State lost, re-synching:')
              for e in ctx.sync():
                  print(e)

class `InputAbsInfo`(minimum=None, maximum=None, fuzz=None, flat=None, resolution=None, value=None)

  Bases: `object`

  A class representing the struct input_absinfo for a given EV_ABS code.

  Any of the attributes may be set to None, those that are None are simply ignored by libevdev.

  Property minimum

    the minimum value for this axis

  Property maximum

    the maximum value for this axis

  Property fuzz

    the fuzz value for this axis

  Property flat

    the flat value for this axis

  Property resolution

    the resolution for this axis

  Property value

    the current value of this axis

exception `InvalidArgumentException`(msg=None)

  Bases: `Exception`

  A function was called with an invalid argument. This indicates a bug in the calling program.

  `message`

    A human-readable error message

exception `InvalidFileError`

  Bases: `Exception`

  A file provided is not a valid file descriptor for libevdev or this device must not have a file descriptor

## libevdev.event module

class `InputEvent`(code, value=None, sec=0, usec=0)

  Bases: `object`

  Represents one input event of type struct input_event as defined in `linux/input.h` and returned by `libevdev_next_event()`.

  Comparison between events can be done via the `matches()` function or by comparing two input events. Two events match when their most precise attribute match and all other attributes are None:

      >>> e = InputEvent(libevdev.EV_REL.REL_X, value=1)
      >>> e == InputEvent(libevdev.EV_REL)
      True
      >>> e == InputEvent(libevdev.EV_ABS)
      True
      >>> e == InputEvent(libevdev.EV_REL.REL_X)
      True
      >>> e == InputEvent(libevdev.EV_REL.REL_Y)
      False
      >>> e == InputEvent(libevdev.EV_REL.REL_X, value=1)
      True
      >>> e == InputEvent(libevdev.EV_REL.REL_X, value=2)
      False

  `code`

    The `EventCode` or `EventType` for this input event

  `value`

    The (optional) value for the event’s axis

  `sec`

    The timestamp, seconds

  `usec`

    The timestamp, microseconds

  property `code`
    Returns

      the EventCode for this event or None

    Return type

      EventCode

  `matches`(code, value=None)
    Parameters

      - code (EventType or EventCode) – the event type or code

      - value – optional, the event value

    Returns

      True if the type matches this event’s type and this event’s code matches the given code (if any) and this event’s value matches the given value (if any)

    Check if an event matches a given event type and/or code. The following invocations show how to match on an event type, an event code and an event code with a specific value:

        if ev.matches(libevdev.EV_REL):
                pass

        if ev.matches(libevdev.EV_REL.REL_X):
                pass

        if ev.matches(libevdev.EV_REL.REL_X, 1):
                pass

  property `type`
    Returns

      the event type for this event

    Return type

      EventType

## Module contents