iLO-manager first main commitgit status

This commit is contained in:
Jiří Stach committed 2026-02-03 15:56:53 +01:00
1 parent e6f4cc04ca
commit 599d8da562
3271 files changed
+550655

No files matched your search

@@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev
======
A binding to libudev.
The :class:`Context` provides the connection to the udev device database
and enumerates devices. Individual devices are represented by the
:class:`Device` class.
Device monitoring is provided by :class:`Monitor` and
:class:`MonitorObserver`. With :mod:`pyudev.pyqt4`, :mod:`pyudev.pyside`,
:mod:`pyudev.glib` and :mod:`pyudev.wx` device monitoring can be integrated
into the event loop of various GUI toolkits.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: LOCAL
from pyudev._errors import (
DeviceNotFoundAtPathError,
DeviceNotFoundByFileError,
DeviceNotFoundByNameError,
DeviceNotFoundByNumberError,
DeviceNotFoundError,
DeviceNotFoundInEnvironmentError,
)
from pyudev._util import udev_version
from pyudev.core import Context, Enumerator
from pyudev.device import Attributes, Device, Devices, Tags
from pyudev.discover import (
DeviceFileHypothesis,
DeviceNameHypothesis,
DeviceNumberHypothesis,
DevicePathHypothesis,
Discovery,
)
from pyudev.monitor import Monitor, MonitorObserver
from pyudev.version import __version__, __version_info__
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib
=================
Wrappers for libraries.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
from . import libc, libudev
@@ -0,0 +1,99 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib._errorcheckers
================================
Error checkers for ctypes wrappers.
"""
# isort: STDLIB
import errno
import os
from ctypes import get_errno
ERRNO_EXCEPTIONS = {
errno.ENOMEM: MemoryError,
errno.EOVERFLOW: OverflowError,
errno.EINVAL: ValueError,
}
def exception_from_errno(errnum):
"""Create an exception from ``errnum``.
``errnum`` is an integral error number.
Return an exception object appropriate to ``errnum``.
"""
exception = ERRNO_EXCEPTIONS.get(errnum)
errorstr = os.strerror(errnum)
if exception is None:
return EnvironmentError(errnum, errorstr)
return exception(errorstr)
def check_negative_errorcode(result, _func, *_args):
"""Error checker for funtions, which return negative error codes.
If ``result`` is smaller than ``0``, it is interpreted as negative error
code, and an appropriate exception is raised:
- ``-ENOMEM`` raises a :exc:`~exceptions.MemoryError`
- ``-EOVERFLOW`` raises a :exc:`~exceptions.OverflowError`
- all other error codes raise :exc:`~exceptions.EnvironmentError`
If result is greater or equal to ``0``, it is returned unchanged.
"""
if result < 0:
# udev returns the *negative* errno code at this point
errnum = -result
raise exception_from_errno(errnum)
return result
def check_errno_on_nonzero_return(result, _func, *_args):
"""Error checker to check the system ``errno`` as returned by
:func:`ctypes.get_errno()`.
If ``result`` is not ``0``, an exception according to this errno is raised.
Otherwise nothing happens.
"""
if result != 0:
errnum = get_errno()
if errnum != 0:
raise exception_from_errno(errnum)
return result
def check_errno_on_null_pointer_return(result, _func, *_args):
"""Error checker to check the system ``errno`` as returned by
:func:`ctypes.get_errno()`.
If ``result`` is a null pointer, an exception according to this errno is
raised. Otherwise nothing happens.
"""
# pylint: disable=invalid-name
if not result:
errnum = get_errno()
if errnum != 0:
raise exception_from_errno(errnum)
return result
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib.libc
======================
Wrappers for libc.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
from ctypes import c_int
from ._errorcheckers import check_errno_on_nonzero_return
FD_PAIR = c_int * 2
SIGNATURES = {
"pipe2": ([FD_PAIR, c_int], c_int),
}
ERROR_CHECKERS = {
"pipe2": check_errno_on_nonzero_return,
}
@@ -0,0 +1,271 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib.libudev
=========================
Wrapper types for libudev. Use ``libudev`` attribute to access libudev
functions.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
from ctypes import POINTER, Structure, c_char, c_char_p, c_int, c_uint, c_ulonglong
from ._errorcheckers import (
check_errno_on_nonzero_return,
check_errno_on_null_pointer_return,
check_negative_errorcode,
)
class udev(Structure): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev`` structure.
"""
udev_p = POINTER(udev) # pylint: disable=invalid-name
class udev_enumerate(
Structure
): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev_enumerate`` structure.
"""
udev_enumerate_p = POINTER(udev_enumerate) # pylint: disable=invalid-name
class udev_list_entry(
Structure
): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev_list_entry`` structure.
"""
udev_list_entry_p = POINTER(udev_list_entry) # pylint: disable=invalid-name
class udev_device(
Structure
): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev_device`` structure.
"""
udev_device_p = POINTER(udev_device) # pylint: disable=invalid-name
class udev_monitor(
Structure
): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev_device`` structure.
"""
udev_monitor_p = POINTER(udev_monitor) # pylint: disable=invalid-name
class udev_hwdb(
Structure
): # pylint: disable=invalid-name,disable=too-few-public-methods
"""
Dummy for ``udev_hwdb`` structure.
"""
udev_hwdb_p = POINTER(udev_hwdb) # pylint: disable=invalid-name
dev_t = c_ulonglong # pylint: disable=invalid-name
SIGNATURES = {
# context
"udev_new": ([], udev_p),
"udev_unref": ([udev_p], None),
"udev_ref": ([udev_p], udev_p),
"udev_get_sys_path": ([udev_p], c_char_p),
"udev_get_dev_path": ([udev_p], c_char_p),
"udev_get_run_path": ([udev_p], c_char_p),
"udev_get_log_priority": ([udev_p], c_int),
"udev_set_log_priority": ([udev_p, c_int], None),
"udev_enumerate_new": ([udev_p], udev_enumerate_p),
"udev_enumerate_ref": ([udev_enumerate_p], udev_enumerate_p),
"udev_enumerate_unref": ([udev_enumerate_p], None),
"udev_enumerate_add_match_subsystem": ([udev_enumerate_p, c_char_p], c_int),
"udev_enumerate_add_nomatch_subsystem": ([udev_enumerate_p, c_char_p], c_int),
"udev_enumerate_add_match_property": (
[udev_enumerate_p, c_char_p, c_char_p],
c_int,
),
"udev_enumerate_add_match_sysattr": ([udev_enumerate_p, c_char_p, c_char_p], c_int),
"udev_enumerate_add_nomatch_sysattr": (
[udev_enumerate_p, c_char_p, c_char_p],
c_int,
),
"udev_enumerate_add_match_tag": ([udev_enumerate_p, c_char_p], c_int),
"udev_enumerate_add_match_sysname": ([udev_enumerate_p, c_char_p], c_int),
"udev_enumerate_add_match_parent": ([udev_enumerate_p, udev_device_p], c_int),
"udev_enumerate_add_match_is_initialized": ([udev_enumerate_p], c_int),
"udev_enumerate_scan_devices": ([udev_enumerate_p], c_int),
"udev_enumerate_get_list_entry": ([udev_enumerate_p], udev_list_entry_p),
# list entries
"udev_list_entry_get_next": ([udev_list_entry_p], udev_list_entry_p),
"udev_list_entry_get_name": ([udev_list_entry_p], c_char_p),
"udev_list_entry_get_value": ([udev_list_entry_p], c_char_p),
# devices
"udev_device_ref": ([udev_device_p], udev_device_p),
"udev_device_unref": ([udev_device_p], None),
"udev_device_new_from_syspath": ([udev_p, c_char_p], udev_device_p),
"udev_device_new_from_subsystem_sysname": (
[udev_p, c_char_p, c_char_p],
udev_device_p,
),
"udev_device_new_from_devnum": ([udev_p, c_char, dev_t], udev_device_p),
"udev_device_new_from_device_id": ([udev_p, c_char_p], udev_device_p),
"udev_device_new_from_environment": ([udev_p], udev_device_p),
"udev_device_get_parent": ([udev_device_p], udev_device_p),
"udev_device_get_parent_with_subsystem_devtype": (
[udev_device_p, c_char_p, c_char_p],
udev_device_p,
),
"udev_device_get_devpath": ([udev_device_p], c_char_p),
"udev_device_get_subsystem": ([udev_device_p], c_char_p),
"udev_device_get_syspath": ([udev_device_p], c_char_p),
"udev_device_get_sysnum": ([udev_device_p], c_char_p),
"udev_device_get_sysname": ([udev_device_p], c_char_p),
"udev_device_get_driver": ([udev_device_p], c_char_p),
"udev_device_get_devtype": ([udev_device_p], c_char_p),
"udev_device_get_devnode": ([udev_device_p], c_char_p),
"udev_device_get_property_value": ([udev_device_p, c_char_p], c_char_p),
"udev_device_get_sysattr_value": ([udev_device_p, c_char_p], c_char_p),
"udev_device_get_devnum": ([udev_device_p], dev_t),
"udev_device_get_action": ([udev_device_p], c_char_p),
"udev_device_get_seqnum": ([udev_device_p], c_ulonglong),
"udev_device_get_is_initialized": ([udev_device_p], c_int),
"udev_device_get_usec_since_initialized": ([udev_device_p], c_ulonglong),
"udev_device_get_devlinks_list_entry": ([udev_device_p], udev_list_entry_p),
"udev_device_get_tags_list_entry": ([udev_device_p], udev_list_entry_p),
"udev_device_get_properties_list_entry": ([udev_device_p], udev_list_entry_p),
"udev_device_get_sysattr_list_entry": ([udev_device_p], udev_list_entry_p),
"udev_device_set_sysattr_value": ([udev_device_p, c_char_p, c_char_p], c_int),
"udev_device_has_tag": ([udev_device_p, c_char_p], c_int),
# monitoring
"udev_monitor_ref": ([udev_monitor_p], udev_monitor_p),
"udev_monitor_unref": ([udev_monitor_p], None),
"udev_monitor_new_from_netlink": ([udev_p, c_char_p], udev_monitor_p),
"udev_monitor_enable_receiving": ([udev_monitor_p], c_int),
"udev_monitor_set_receive_buffer_size": ([udev_monitor_p, c_int], c_int),
"udev_monitor_get_fd": ([udev_monitor_p], c_int),
"udev_monitor_receive_device": ([udev_monitor_p], udev_device_p),
"udev_monitor_filter_add_match_subsystem_devtype": (
[udev_monitor_p, c_char_p, c_char_p],
c_int,
),
"udev_monitor_filter_add_match_tag": ([udev_monitor_p, c_char_p], c_int),
"udev_monitor_filter_update": ([udev_monitor_p], c_int),
"udev_monitor_filter_remove": ([udev_monitor_p], c_int),
# hwdb
"udev_hwdb_ref": ([udev_hwdb_p], udev_hwdb_p),
"udev_hwdb_unref": ([udev_hwdb_p], None),
"udev_hwdb_new": ([udev_p], udev_hwdb_p),
"udev_hwdb_get_properties_list_entry": (
[udev_hwdb_p, c_char_p, c_uint],
udev_list_entry_p,
),
}
ERROR_CHECKERS = {
"udev_device_get_action": None,
"udev_device_get_devlinks_list_entry": None,
"udev_device_get_devnode": None,
"udev_device_get_devnum": None,
"udev_device_get_devpath": None,
"udev_device_get_devtype": None,
"udev_device_get_driver": None,
"udev_device_get_is_initialized": None,
"udev_device_get_parent": None,
"udev_device_get_parent_with_subsystem_devtype": None,
"udev_device_get_properties_list_entry": None,
"udev_device_get_property_value": None,
"udev_device_get_seqnum": None,
"udev_device_get_subsystem": None,
"udev_device_get_sysattr_list_entry": None,
"udev_device_get_sysattr_value": None,
"udev_device_get_sysname": None,
"udev_device_get_sysnum": None,
"udev_device_get_syspath": None,
"udev_device_get_tags_list_entry": None,
"udev_device_get_usec_since_initialized": None,
"udev_device_has_tag": None,
"udev_device_new_from_device_id": None,
"udev_device_new_from_devnum": None,
"udev_device_new_from_environment": None,
"udev_device_new_from_subsystem_sysname": None,
"udev_device_new_from_syspath": None,
"udev_device_ref": None,
"udev_device_unref": None,
"udev_device_set_sysattr_value": check_negative_errorcode,
"udev_enumerate_add_match_parent": check_negative_errorcode,
"udev_enumerate_add_match_subsystem": check_negative_errorcode,
"udev_enumerate_add_nomatch_subsystem": check_negative_errorcode,
"udev_enumerate_add_match_property": check_negative_errorcode,
"udev_enumerate_add_match_sysattr": check_negative_errorcode,
"udev_enumerate_add_nomatch_sysattr": check_negative_errorcode,
"udev_enumerate_add_match_tag": check_negative_errorcode,
"udev_enumerate_add_match_sysname": check_negative_errorcode,
"udev_enumerate_add_match_is_initialized": check_negative_errorcode,
"udev_enumerate_get_list_entry": None,
"udev_enumerate_new": None,
"udev_enumerate_ref": None,
"udev_enumerate_scan_devices": None,
"udev_enumerate_unref": None,
"udev_get_dev_path": None,
"udev_get_log_priority": None,
"udev_get_run_path": None,
"udev_get_sys_path": None,
"udev_hwdb_get_properties_list_entry": None,
"udev_hwdb_new": None,
"udev_hwdb_ref": None,
"udev_hwdb_unref": None,
"udev_list_entry_get_name": None,
"udev_list_entry_get_next": None,
"udev_list_entry_get_value": None,
"udev_monitor_set_receive_buffer_size": check_errno_on_nonzero_return,
# libudev doc says, enable_receiving returns a negative errno, but tests
# show that this is not reliable, so query the real error code
"udev_monitor_enable_receiving": check_errno_on_nonzero_return,
"udev_monitor_receive_device": check_errno_on_null_pointer_return,
"udev_monitor_ref": None,
"udev_monitor_filter_add_match_subsystem_devtype": check_negative_errorcode,
"udev_monitor_filter_add_match_tag": check_negative_errorcode,
"udev_monitor_filter_update": check_errno_on_nonzero_return,
"udev_monitor_filter_remove": check_errno_on_nonzero_return,
"udev_monitor_get_fd": None,
"udev_monitor_new_from_netlink": None,
"udev_monitor_unref": None,
"udev_new": None,
"udev_ref": None,
"udev_set_log_priority": None,
"udev_unref": None,
}
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._ctypeslib.utils
=======================
Utilities for loading ctypeslib.
.. moduleauthor:: Anne Mulhern <amulhern@redhat.com>
"""
# isort: STDLIB
from ctypes import CDLL
from ctypes.util import find_library
def load_ctypes_library(name, signatures, error_checkers):
"""
Load library ``name`` and return a :class:`ctypes.CDLL` object for it.
:param str name: the library name
:param signatures: signatures of methods
:type signatures: dict of str * (tuple of (list of type) * type)
:param error_checkers: error checkers for methods
:type error_checkers: dict of str * ((int * ptr * arglist) -> int)
The library has errno handling enabled.
Important functions are given proper signatures and return types to support
type checking and argument conversion.
:returns: a loaded library
:rtype: ctypes.CDLL
:raises ImportError: if the library is not found
"""
library_name = find_library(name)
if not library_name:
raise ImportError(f"No library named {name}")
lib = CDLL(library_name, use_errno=True)
# Add function signatures
for funcname, signature in signatures.items():
function = getattr(lib, funcname, None)
if function:
argtypes, restype = signature
function.argtypes = argtypes
function.restype = restype
errorchecker = error_checkers.get(funcname)
if errorchecker:
function.errcheck = errorchecker
return lib
@@ -0,0 +1,184 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.device._errors
=====================
Errors raised by Device methods.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
import abc
class DeviceError(Exception):
"""
Any error raised when messing around w/ or trying to discover devices.
"""
__metaclass__ = abc.ABCMeta
class DeviceNotFoundError(DeviceError):
"""
An exception indicating that no :class:`Device` was found.
.. versionchanged:: 0.5
Rename from ``NoSuchDeviceError`` to its current name.
"""
__metaclass__ = abc.ABCMeta
class DeviceNotFoundAtPathError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
found at a given path.
"""
def __init__(self, sys_path):
DeviceNotFoundError.__init__(self, sys_path)
@property
def sys_path(self):
"""
The path that caused this error as string.
"""
return self.args[0]
def __str__(self):
return f"No device at {self.sys_path!r}"
class DeviceNotFoundByFileError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
found from the given filename.
"""
class DeviceNotFoundByInterfaceIndexError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
from the given interface index.
"""
class DeviceNotFoundByKernelDeviceError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
from the given kernel device string.
The format of the kernel device string is defined in the
systemd.journal-fields man pages.
"""
class DeviceNotFoundByNameError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
found with a given name.
"""
def __init__(self, subsystem, sys_name):
DeviceNotFoundError.__init__(self, subsystem, sys_name)
@property
def subsystem(self):
"""
The subsystem that caused this error as string.
"""
return self.args[0]
@property
def sys_name(self):
"""
The sys name that caused this error as string.
"""
return self.args[1]
def __str__(self):
return f"No device {self.sys_name!r} in {self.subsystem!r}"
class DeviceNotFoundByNumberError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` was found
for a given device number.
"""
def __init__(self, typ, number):
DeviceNotFoundError.__init__(self, typ, number)
@property
def device_type(self):
"""
The device type causing this error as string. Either ``'char'`` or
``'block'``.
"""
return self.args[0]
@property
def device_number(self):
"""
The device number causing this error as integer.
"""
return self.args[1]
def __str__(self):
return f"No {self.device_type} device with number {self.device_number}"
class DeviceNotFoundInEnvironmentError(DeviceNotFoundError):
"""
A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` could
be constructed from the process environment.
"""
def __str__(self):
return "No device found in environment"
class DeviceValueError(DeviceError):
"""
Raised when a parameter has an unacceptable value.
May also be raised when the parameter has an unacceptable type.
"""
_FMT_STR = "value '%s' for parameter %s is unacceptable"
def __init__(self, value, param, msg=None):
"""
Initializer.
:param object value: the value
:param str param: the parameter
:param str msg: an explanatory message
"""
# pylint: disable=super-init-not-called
self._value = value
self._param = param
self._msg = msg
def __str__(self):
if self._msg:
fmt_str = self._FMT_STR + ": %s"
return fmt_str % (self._value, self._param, self._msg)
return self._FMT_STR % (self._value, self._param)
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._os
==========
Extras to compensate for deficiencies in python os module.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
from . import pipe, poll
@@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._os.pipe
===============
Fallback implementations for pipe.
1. pipe2 from python os module
2. pipe2 from libc
3. pipe from python os module
The Pipe class wraps the chosen implementation.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
import fcntl
import os
from functools import partial
# isort: LOCAL
from pyudev._ctypeslib.libc import ERROR_CHECKERS, FD_PAIR, SIGNATURES
from pyudev._ctypeslib.utils import load_ctypes_library
# Define O_CLOEXEC, if not present in os already
O_CLOEXEC = getattr(os, "O_CLOEXEC", 0o2000000)
def _pipe2_ctypes(libc, flags):
"""A ``pipe2`` implementation using ``pipe2`` from ctypes.
``libc`` is a :class:`ctypes.CDLL` object for libc. ``flags`` is an
integer providing the flags to ``pipe2``.
Return a pair of file descriptors ``(r, w)``.
"""
fds = FD_PAIR()
libc.pipe2(fds, flags)
return fds[0], fds[1]
def _pipe2_by_pipe(flags):
"""A ``pipe2`` implementation using :func:`os.pipe`.
``flags`` is an integer providing the flags to ``pipe2``.
.. warning::
This implementation is not atomic!
Return a pair of file descriptors ``(r, w)``.
"""
fds = os.pipe()
if flags & os.O_NONBLOCK != 0:
for file_descriptor in fds:
set_fd_status_flag(file_descriptor, os.O_NONBLOCK)
if flags & O_CLOEXEC != 0:
for file_descriptor in fds:
set_fd_flag(file_descriptor, O_CLOEXEC)
return fds
def _get_pipe2_implementation():
"""
Find the appropriate implementation for ``pipe2``.
Return a function implementing ``pipe2``."""
if hasattr(os, "pipe2"):
return os.pipe2 # pylint: disable=no-member
try:
libc = load_ctypes_library("libc", SIGNATURES, ERROR_CHECKERS)
return (
partial(_pipe2_ctypes, libc) if hasattr(libc, "pipe2") else _pipe2_by_pipe
)
except ImportError:
return _pipe2_by_pipe
_PIPE2 = _get_pipe2_implementation()
def set_fd_flag(fd, flag): # pylint: disable=invalid-name
"""Set a flag on a file descriptor.
``fd`` is the file descriptor or file object, ``flag`` the flag as integer.
"""
flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0)
fcntl.fcntl(fd, fcntl.F_SETFD, flags | flag)
def set_fd_status_flag(fd, flag): # pylint: disable=invalid-name
"""Set a status flag on a file descriptor.
``fd`` is the file descriptor or file object, ``flag`` the flag as integer.
"""
flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | flag)
class Pipe:
"""A unix pipe.
A pipe object provides two file objects: :attr:`source` is a readable file
object, and :attr:`sink` a writeable. Bytes written to :attr:`sink` appear
at :attr:`source`.
Open a pipe with :meth:`open()`.
"""
@classmethod
def open(cls):
"""Open and return a new :class:`Pipe`.
The pipe uses non-blocking IO."""
source, sink = _PIPE2(os.O_NONBLOCK | O_CLOEXEC)
return cls(source, sink)
def __init__(self, source_fd, sink_fd):
"""Create a new pipe object from the given file descriptors.
``source_fd`` is a file descriptor for the readable side of the pipe,
``sink_fd`` is a file descriptor for the writeable side."""
self.source = os.fdopen(source_fd, "rb", 0)
self.sink = os.fdopen(sink_fd, "wb", 0)
def close(self):
"""Closes both sides of the pipe."""
try:
self.source.close()
finally:
self.sink.close()
@@ -0,0 +1,113 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._os.poll
===============
Operating system interface for pyudev.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
import select
# isort: LOCAL
from pyudev._util import eintr_retry_call
class Poll:
"""A poll object.
This object essentially provides a more convenient interface around
:class:`select.poll`.
"""
_EVENT_TO_MASK = {"r": select.POLLIN, "w": select.POLLOUT}
@staticmethod
def _has_event(events, event):
return events & event != 0
@classmethod
def for_events(cls, *events):
"""Listen for ``events``.
``events`` is a list of ``(fd, event)`` pairs, where ``fd`` is a file
descriptor or file object and ``event`` either ``'r'`` or ``'w'``. If
``r``, listen for whether that is ready to be read. If ``w``, listen
for whether the channel is ready to be written to.
"""
notifier = eintr_retry_call(select.poll)
for fd, event in events: # pylint: disable=invalid-name
mask = cls._EVENT_TO_MASK.get(event)
if not mask:
raise ValueError(f"Unknown event type: {repr(event)}")
notifier.register(fd, mask)
return cls(notifier)
def __init__(self, notifier):
"""Create a poll object for the given ``notifier``.
``notifier`` is the :class:`select.poll` object wrapped by the new poll
object.
"""
self._notifier = notifier
def poll(self, timeout=None):
"""Poll for events.
``timeout`` is an integer specifying how long to wait for events (in
milliseconds). If omitted, ``None`` or negative, wait until an event
occurs.
Return a list of all events that occurred before ``timeout``, where
each event is a pair ``(fd, event)``. ``fd`` is the integral file
descriptor, and ``event`` a string indicating the event type. If
``'r'``, there is data to read from ``fd``. If ``'w'``, ``fd`` is
writable without blocking now. If ``'h'``, the file descriptor was
hung up (i.e. the remote side of a pipe was closed).
"""
# Return a list to allow clients to determine whether there are any
# events at all with a simple truthiness test.
return list(self._parse_events(eintr_retry_call(self._notifier.poll, timeout)))
def _parse_events(self, events):
"""Parse ``events``.
``events`` is a list of events as returned by
:meth:`select.poll.poll()`.
Yield all parsed events.
"""
for fd, event_mask in events: # pylint: disable=invalid-name
if self._has_event(event_mask, select.POLLNVAL):
raise IOError(f"File descriptor not open: {repr(fd)}")
if self._has_event(event_mask, select.POLLERR):
raise IOError(f"Error while polling fd: {repr(fd)}")
if self._has_event(event_mask, select.POLLIN):
yield fd, "r"
if self._has_event(event_mask, select.POLLOUT):
yield fd, "w"
if self._has_event(event_mask, select.POLLHUP):
yield fd, "h"
@@ -0,0 +1,208 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._qt_base
===============
Base mixin class for Qt4,Qt5 support.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: LOCAL
from pyudev.device import Device
class MonitorObserverMixin:
"""
Base mixin for pyqt monitor observers.
"""
# pylint: disable=too-few-public-methods
def _setup_notifier(self, monitor, notifier_class):
self.monitor = monitor
self.notifier = notifier_class(monitor.fileno(), notifier_class.Read, self)
self.notifier.activated[int].connect(self._process_udev_event)
@property
def enabled(self):
"""
Whether this observer is enabled or not.
If ``True`` (the default), this observer is enabled, and emits events.
Otherwise it is disabled and does not emit any events. This merely
reflects the state of the ``enabled`` property of the underlying
:attr:`notifier`.
.. versionadded:: 0.14
"""
return self.notifier.isEnabled()
@enabled.setter
def enabled(self, value):
self.notifier.setEnabled(value)
def _process_udev_event(self):
"""
Attempt to receive a single device event from the monitor, process
the event and emit corresponding signals.
Called by ``QSocketNotifier``, if data is available on the udev
monitoring socket.
"""
device = self.monitor.poll(timeout=0)
if device is not None:
self._emit_event(device)
def _emit_event(self, device):
self.deviceEvent.emit(device)
class QUDevMonitorObserverMixin(MonitorObserverMixin):
"""
Obsolete monitor observer mixin.
"""
# pylint: disable=too-few-public-methods
def _setup_notifier(self, monitor, notifier_class):
MonitorObserverMixin._setup_notifier(self, monitor, notifier_class)
self._action_signal_map = {
"add": self.deviceAdded,
"remove": self.deviceRemoved,
"change": self.deviceChanged,
"move": self.deviceMoved,
}
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use pyudev.pyqt4.MonitorObserver instead.",
DeprecationWarning,
)
def _emit_event(self, device):
self.deviceEvent.emit(device.action, device)
signal = self._action_signal_map.get(device.action)
if signal is not None:
signal.emit(device)
def make_init(qobject, socket_notifier):
"""
Generates an initializer to observer the given ``monitor``
(a :class:`~pyudev.Monitor`):
``parent`` is the parent :class:`~PyQt{4,5}.QtCore.QObject` of this
object. It is passed unchanged to the inherited constructor of
:class:`~PyQt{4,5}.QtCore.QObject`.
"""
def __init__(self, monitor, parent=None):
qobject.__init__(self, parent)
# pylint: disable=protected-access
self._setup_notifier(monitor, socket_notifier)
return __init__
class MonitorObserverGenerator:
"""
Class to generate a MonitorObserver class.
"""
# pylint: disable=too-few-public-methods
@staticmethod
def make_monitor_observer(qobject, signal, socket_notifier):
"""Generates an observer for device events integrating into the
PyQt{4,5} mainloop.
This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
events into Qt signals:
>>> from pyudev import Context, Monitor
>>> from pyudev.pyqt4 import MonitorObserver
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
>>> monitor.filter_by(subsystem='input')
>>> observer = MonitorObserver(monitor)
>>> def device_event(device):
... print('event {0} on device {1}'.format(device.action, device))
>>> observer.deviceEvent.connect(device_event)
>>> monitor.start()
This class is a child of :class:`~{PySide, PyQt{4,5}}.QtCore.QObject`.
"""
return type(
str("MonitorObserver"),
(qobject, MonitorObserverMixin),
{
str("__init__"): make_init(qobject, socket_notifier),
str("deviceEvent"): signal(Device),
},
)
class QUDevMonitorObserverGenerator:
"""
Class to generate a MonitorObserver class.
"""
# pylint: disable=too-few-public-methods
@staticmethod
def make_monitor_observer(qobject, signal, socket_notifier):
"""Generates an observer for device events integrating into the
PyQt{4,5} mainloop.
This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
events into Qt signals:
>>> from pyudev import Context, Monitor
>>> from pyudev.pyqt4 import MonitorObserver
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
>>> monitor.filter_by(subsystem='input')
>>> observer = MonitorObserver(monitor)
>>> def device_event(device):
... print('event {0} on device {1}'.format(device.action, device))
>>> observer.deviceEvent.connect(device_event)
>>> monitor.start()
This class is a child of :class:`~{PyQt{4,5}, PySide}.QtCore.QObject`.
"""
return type(
str("QUDevMonitorObserver"),
(qobject, QUDevMonitorObserverMixin),
{
str("__init__"): make_init(qobject, socket_notifier),
#: emitted upon arbitrary device events
str("deviceEvent"): signal(str, Device),
#: emitted if a device was added
str("deviceAdded"): signal(Device),
#: emitted if a device was removed
str("deviceRemoved"): signal(Device),
#: emitted if a device was changed
str("deviceChanged"): signal(Device),
#: emitted if a device was moved
str("deviceMoved"): signal(Device),
},
)
@@ -0,0 +1,191 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev._util
============
Internal utilities
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
import errno
import os
import stat
import sys
from subprocess import check_output
def ensure_byte_string(value):
"""
Return the given ``value`` as bytestring.
If the given ``value`` is not a byte string, but a real unicode string, it
is encoded with the filesystem encoding (as in
:func:`sys.getfilesystemencoding()`).
"""
if not isinstance(value, bytes):
value = value.encode(sys.getfilesystemencoding())
return value
def ensure_unicode_string(value):
"""
Return the given ``value`` as unicode string.
If the given ``value`` is not a unicode string, but a byte string, it is
decoded with the filesystem encoding (as in
:func:`sys.getfilesystemencoding()`).
"""
if not isinstance(value, str):
value = value.decode(sys.getfilesystemencoding())
return value
def property_value_to_bytes(value):
"""
Return a byte string, which represents the given ``value`` in a way
suitable as raw value of an udev property.
If ``value`` is a boolean object, it is converted to ``'1'`` or ``'0'``,
depending on whether ``value`` is ``True`` or ``False``. If ``value`` is a
byte string already, it is returned unchanged. Anything else is simply
converted to a unicode string, and then passed to
:func:`ensure_byte_string`.
"""
# udev represents boolean values as 1 or 0, therefore an explicit
# conversion to int is required for boolean values
if isinstance(value, bool):
value = int(value)
if isinstance(value, bytes):
return value
return ensure_byte_string(str(value))
def string_to_bool(value):
"""
Convert the given unicode string ``value`` to a boolean object.
If ``value`` is ``'1'``, ``True`` is returned. If ``value`` is ``'0'``,
``False`` is returned. Any other value raises a
:exc:`~exceptions.ValueError`.
"""
if value not in ("1", "0"):
raise ValueError(f"Not a boolean value: {value!r}")
return value == "1"
def udev_list_iterate(libudev, entry):
"""
Iteration helper for udev list entry objects.
Yield a tuple ``(name, value)``. ``name`` and ``value`` are bytestrings
containing the name and the value of the list entry. The exact contents
depend on the list iterated over.
"""
while entry:
name = libudev.udev_list_entry_get_name(entry)
value = libudev.udev_list_entry_get_value(entry)
yield (name, value)
entry = libudev.udev_list_entry_get_next(entry)
def get_device_type(filename):
"""
Get the device type of a device file.
``filename`` is a string containing the path of a device file.
Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
``filename`` is a block device. Raise :exc:`~exceptions.ValueError` if
``filename`` is no device file at all. Raise
:exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
its metadata was inaccessible.
.. versionadded:: 0.15
"""
mode = os.stat(filename).st_mode
if stat.S_ISCHR(mode):
return "char"
if stat.S_ISBLK(mode):
return "block"
raise ValueError(f"not a device file: {filename!r}")
def eintr_retry_call(func, *args, **kwargs):
"""
Handle interruptions to an interruptible system call.
Run an interruptible system call in a loop and retry if it raises EINTR.
The signal calls that may raise EINTR prior to Python 3.5 are listed in
PEP 0475. Any calls to these functions must be wrapped in eintr_retry_call
in order to handle EINTR returns in older versions of Python.
This function is safe to use under Python 3.5 and newer since the wrapped
function will simply return without raising EINTR.
This function is based on _eintr_retry_call in python's subprocess.py.
"""
# select.error inherits from Exception instead of OSError in Python 2
# isort: STDLIB
import select # pylint: disable=import-outside-toplevel
while True:
try:
return func(*args, **kwargs)
except (OSError, IOError, select.error) as err:
# If this is not an IOError or OSError, it's the old select.error
# type, which means that the errno is only accessible via subscript
if isinstance(err, (OSError, IOError)):
error_code = err.errno
else:
error_code = err.args[0]
if error_code == errno.EINTR:
continue
raise
def udev_version():
"""
Get the version of the underlying udev library.
udev doesn't use a standard major-minor versioning scheme, but instead
labels releases with a single consecutive number. Consequently, the
version number returned by this function is a single integer, and not a
tuple (like for instance the interpreter version in
:data:`sys.version_info`).
As libudev itself does not provide a function to query the version number,
this function calls the ``udevadm`` utility, so be prepared to catch
:exc:`~exceptions.EnvironmentError` and
:exc:`~subprocess.CalledProcessError` if you call this function.
Return the version number as single integer. Raise
:exc:`~exceptions.ValueError`, if the version number retrieved from udev
could not be converted to an integer. Raise
:exc:`~exceptions.EnvironmentError`, if ``udevadm`` was not found, or could
not be executed. Raise :exc:`subprocess.CalledProcessError`, if
``udevadm`` returned a non-zero exit code. On Python 2.7 or newer, the
``output`` attribute of this exception is correctly set.
.. versionadded:: 0.8
"""
output = ensure_unicode_string(check_output(["udevadm", "--version"]))
return int(output.strip())
@@ -0,0 +1,391 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.core
===========
Core types and functions of :mod:`pyudev`.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: LOCAL
from pyudev._ctypeslib.libudev import ERROR_CHECKERS, SIGNATURES
from pyudev._ctypeslib.utils import load_ctypes_library
from pyudev._errors import DeviceNotFoundAtPathError
from pyudev._util import (
ensure_byte_string,
ensure_unicode_string,
property_value_to_bytes,
udev_list_iterate,
)
from pyudev.device import Devices
class Context:
"""
A device database connection.
This class represents a connection to the udev device database, and is
really *the* central object to access udev. You need an instance of this
class for almost anything else in pyudev.
This class itself gives access to various udev configuration data (e.g.
:attr:`sys_path`, :attr:`device_path`), and provides device enumeration
(:meth:`list_devices()`).
Instances of this class can directly be given as ``udev *`` to functions
wrapped through :mod:`ctypes`.
"""
def __init__(self):
"""
Create a new context.
"""
self._libudev = load_ctypes_library("udev", SIGNATURES, ERROR_CHECKERS)
self._as_parameter_ = self._libudev.udev_new()
def __del__(self):
if hasattr(self, "_libudev"):
self._libudev.udev_unref(self)
@property
def sys_path(self):
"""
The ``sysfs`` mount point defaulting to ``/sys'`` as unicode string.
"""
if hasattr(self._libudev, "udev_get_sys_path"):
return ensure_unicode_string(self._libudev.udev_get_sys_path(self))
return "/sys" # Fixed path since udev 183
@property
def device_path(self):
"""
The device directory path defaulting to ``/dev`` as unicode string.
"""
if hasattr(self._libudev, "udev_get_dev_path"):
return ensure_unicode_string(self._libudev.udev_get_dev_path(self))
return "/dev" # Fixed path since udev 183
@property
def run_path(self):
"""
The run runtime directory path defaulting to ``/run`` as unicode
string.
.. udevversion:: 167
.. versionadded:: 0.10
"""
if hasattr(self._libudev, "udev_get_run_path"):
return ensure_unicode_string(self._libudev.udev_get_run_path(self))
return "/run/udev"
@property
def log_priority(self):
"""
The logging priority of the interal logging facitility of udev as
integer with a standard :mod:`syslog` priority. Assign to this
property to change the logging priority.
UDev uses the standard :mod:`syslog` priorities. Constants for these
priorities are defined in the :mod:`syslog` module in the standard
library:
>>> import syslog
>>> context = pyudev.Context()
>>> context.log_priority = syslog.LOG_DEBUG
.. versionadded:: 0.9
"""
return self._libudev.udev_get_log_priority(self)
@log_priority.setter
def log_priority(self, value):
"""
Set the log priority.
:param int value: the log priority.
"""
self._libudev.udev_set_log_priority(self, value)
def list_devices(self, **kwargs):
"""
List all available devices.
The arguments of this method are the same as for
:meth:`Enumerator.match()`. In fact, the arguments are simply passed
straight to method :meth:`~Enumerator.match()`.
This function creates and returns an :class:`Enumerator` object,
that can be used to filter the list of devices, and eventually
retrieve :class:`Device` objects representing matching devices.
.. versionchanged:: 0.8
Accept keyword arguments now for easy matching.
"""
return Enumerator(self).match(**kwargs)
class Enumerator:
"""
A filtered iterable of devices.
To retrieve devices, simply iterate over an instance of this class.
This operation yields :class:`Device` objects representing the available
devices.
Before iteration the device list can be filtered by subsystem or by
property values using :meth:`match_subsystem` and
:meth:`match_property`. Multiple subsystem (property) filters are
combined using a logical OR, filters of different types are combined
using a logical AND. The following filter for instance::
devices.match_subsystem('block').match_property(
'ID_TYPE', 'disk').match_property('DEVTYPE', 'disk')
means the following::
subsystem == 'block' and (ID_TYPE == 'disk' or DEVTYPE == 'disk')
Once added, a filter cannot be removed anymore. Create a new object
instead.
Instances of this class can directly be given as given ``udev_enumerate *``
to functions wrapped through :mod:`ctypes`.
"""
def __init__(self, context):
"""
Create a new enumerator with the given ``context`` (a
:class:`Context` instance).
While you can create objects of this class directly, this is not
recommended. Call :method:`Context.list_devices()` instead.
"""
if not isinstance(context, Context):
raise TypeError("Invalid context object")
self.context = context
self._as_parameter_ = context._libudev.udev_enumerate_new(context)
self._libudev = context._libudev
def __del__(self):
self._libudev.udev_enumerate_unref(self)
def match(self, **kwargs):
"""
Include devices according to the rules defined by the keyword
arguments. These keyword arguments are interpreted as follows:
- The value for the keyword argument ``subsystem`` is forwarded to
:meth:`match_subsystem()`.
- The value for the keyword argument ``sys_name`` is forwared to
:meth:`match_sys_name()`.
- The value for the keyword argument ``tag`` is forwared to
:meth:`match_tag()`.
- The value for the keyword argument ``parent`` is forwared to
:meth:`match_parent()`.
- All other keyword arguments are forwareded one by one to
:meth:`match_property()`. The keyword argument itself is interpreted
as property name, the value of the keyword argument as the property
value.
All keyword arguments are optional, calling this method without no
arguments at all is simply a noop.
Return the instance again.
.. versionadded:: 0.8
.. versionchanged:: 0.13
Add ``parent`` keyword.
"""
subsystem = kwargs.pop("subsystem", None)
if subsystem is not None:
self.match_subsystem(subsystem)
sys_name = kwargs.pop("sys_name", None)
if sys_name is not None:
self.match_sys_name(sys_name)
tag = kwargs.pop("tag", None)
if tag is not None:
self.match_tag(tag)
parent = kwargs.pop("parent", None)
if parent is not None:
self.match_parent(parent)
for prop, value in kwargs.items():
self.match_property(prop, value)
return self
def match_subsystem(self, subsystem, nomatch=False):
"""
Include all devices, which are part of the given ``subsystem``.
``subsystem`` is either a unicode string or a byte string, containing
the name of the subsystem. If ``nomatch`` is ``True`` (default is
``False``), the match is inverted: A device is only included if it is
*not* part of the given ``subsystem``.
Note that, if a device has no subsystem, it is not included either
with value of ``nomatch`` True or with value of ``nomatch`` False.
Return the instance again.
"""
match = (
self._libudev.udev_enumerate_add_nomatch_subsystem
if nomatch
else self._libudev.udev_enumerate_add_match_subsystem
)
match(self, ensure_byte_string(subsystem))
return self
def match_sys_name(self, sys_name):
"""
Include all devices with the given name.
``sys_name`` is a byte or unicode string containing the device name.
Return the instance again.
.. versionadded:: 0.8
"""
self._libudev.udev_enumerate_add_match_sysname(
self, ensure_byte_string(sys_name)
)
return self
def match_property(self, prop, value):
"""
Include all devices, whose ``prop`` has the given ``value``.
``prop`` is either a unicode string or a byte string, containing
the name of the property to match. ``value`` is a property value,
being one of the following types:
- :func:`int`
- :func:`bool`
- A byte string
- Anything convertable to a unicode string (including a unicode string
itself)
Return the instance again.
"""
self._libudev.udev_enumerate_add_match_property(
self, ensure_byte_string(prop), property_value_to_bytes(value)
)
return self
def match_attribute(self, attribute, value, nomatch=False):
"""
Include all devices, whose ``attribute`` has the given ``value``.
``attribute`` is either a unicode string or a byte string, containing
the name of a sys attribute to match. ``value`` is an attribute value,
being one of the following types:
- :func:`int`,
- :func:`bool`
- A byte string
- Anything convertable to a unicode string (including a unicode string
itself)
If ``nomatch`` is ``True`` (default is ``False``), the match is
inverted: A device is include if the ``attribute`` does *not* match
the given ``value``.
.. note::
If ``nomatch`` is ``True``, devices which do not have the given
``attribute`` at all are also included. In other words, with
``nomatch=True`` the given ``attribute`` is *not* guaranteed to
exist on all returned devices.
Return the instance again.
"""
match = (
self._libudev.udev_enumerate_add_match_sysattr
if not nomatch
else self._libudev.udev_enumerate_add_nomatch_sysattr
)
match(self, ensure_byte_string(attribute), property_value_to_bytes(value))
return self
def match_tag(self, tag):
"""
Include all devices, which have the given ``tag`` attached.
``tag`` is a byte or unicode string containing the tag name.
Return the instance again.
.. udevversion:: 154
.. versionadded:: 0.6
"""
self._libudev.udev_enumerate_add_match_tag(self, ensure_byte_string(tag))
return self
def match_is_initialized(self):
"""
Include only devices, which are initialized.
Initialized devices have properly set device node permissions and
context, and are (in case of network devices) fully renamed.
Currently this will not affect devices which do not have device nodes
and are not network interfaces.
Return the instance again.
.. seealso:: :attr:`Device.is_initialized`
.. udevversion:: 165
.. versionadded:: 0.8
"""
self._libudev.udev_enumerate_add_match_is_initialized(self)
return self
def match_parent(self, parent):
"""
Include all devices on the subtree of the given ``parent`` device.
The ``parent`` device itself is also included.
``parent`` is a :class:`~pyudev.Device`.
Return the instance again.
.. udevversion:: 172
.. versionadded:: 0.13
"""
self._libudev.udev_enumerate_add_match_parent(self, parent)
return self
def __iter__(self):
"""
Iterate over all matching devices.
Yield :class:`Device` objects.
"""
self._libudev.udev_enumerate_scan_devices(self)
entry = self._libudev.udev_enumerate_get_list_entry(self)
for name, _ in udev_list_iterate(self._libudev, entry):
try:
yield Devices.from_sys_path(self.context, name)
except DeviceNotFoundAtPathError:
continue
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.device
=============
Device class implementation of :mod:`pyudev`.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
from ._device import Attributes, Device, Devices, Tags
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,382 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.discover
===============
Tools to discover a device given limited information.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
# isort: STDLIB
import abc
import functools
import os
import re
# isort: LOCAL
from pyudev._errors import DeviceNotFoundError
from pyudev.device import Devices
def wrap_exception(func):
"""
Allow Device discovery methods to return None instead of raising an
exception.
"""
@functools.wraps(func)
def the_func(*args, **kwargs):
"""
Returns result of calling ``func`` on ``args``, ``kwargs``.
Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
"""
try:
return func(*args, **kwargs)
except DeviceNotFoundError:
return None
return the_func
class Hypothesis:
"""
Represents a hypothesis about the meaning of the device identifier.
"""
__metaclass__ = abc.ABCMeta
@classmethod
@abc.abstractmethod
def match(cls, value): # pragma: no cover
"""
Match the given string according to the hypothesis.
The purpose of this method is to obtain a value corresponding to
``value`` if that is possible. It may use a regular expression, but
in general it should just return ``value`` and let the lookup method
sort out the rest.
:param str value: the string to inspect
:returns: the matched thing or None if unmatched
:rtype: the type of lookup's key parameter or NoneType
"""
raise NotImplementedError()
@classmethod
@abc.abstractmethod
def lookup(cls, context, key): # pragma: no cover
"""
Lookup the given string according to the hypothesis.
:param Context context: the pyudev context
:param key: a key with which to lookup the device
:type key: the type of match's return value if not None
:returns: a list of Devices obtained
:rtype: frozenset of :class:`Device`
"""
raise NotImplementedError()
@classmethod
def setup(cls, context):
"""
A potentially expensive method that may allow an :class:`Hypothesis`
to find devices more rapidly or to find a device that it would
otherwise miss.
:param Context context: the pyudev context
"""
@classmethod
def get_devices(cls, context, value):
"""
Get any devices that may correspond to the given string.
:param Context context: the pyudev context
:param str value: the value to look for
:returns: a list of devices obtained
:rtype: set of :class:`Device`
"""
key = cls.match(value)
return cls.lookup(context, key) if key is not None else frozenset()
class DeviceNumberHypothesis(Hypothesis):
"""
Represents the hypothesis that the device is a device number.
The device may be separated into major/minor number or a composite number.
"""
@classmethod
def _match_major_minor(cls, value):
"""
Match the number under the assumption that it is a major,minor pair.
:param str value: value to match
:returns: the device number or None
:rtype: int or NoneType
"""
major_minor_re = re.compile(r"^(?P<major>\d+)(\D+)(?P<minor>\d+)$")
match = major_minor_re.match(value)
return match and os.makedev(
int(match.group("major")), int(match.group("minor"))
)
@classmethod
def _match_number(cls, value):
"""
Match the number under the assumption that it is a single number.
:param str value: value to match
:returns: the device number or None
:rtype: int or NoneType
"""
number_re = re.compile(r"^(?P<number>\d+)$")
match = number_re.match(value)
return match and int(match.group("number"))
@classmethod
def match(cls, value):
"""
Match the number under the assumption that it is a device number.
:returns: the device number or None
:rtype: int or NoneType
"""
return cls._match_major_minor(value) or cls._match_number(value)
@classmethod
def find_subsystems(cls, context):
"""
Find subsystems in /sys/dev.
:param Context context: the context
:returns: a lis of available subsystems
:rtype: list of str
"""
sys_path = context.sys_path
return os.listdir(os.path.join(sys_path, "dev"))
@classmethod
def lookup(cls, context, key):
"""
Lookup by the device number.
:param Context context: the context
:param int key: the device number
:returns: a list of matching devices
:rtype: frozenset of :class:`Device`
"""
func = wrap_exception(Devices.from_device_number)
res = (func(context, s, key) for s in cls.find_subsystems(context))
return frozenset(r for r in res if r is not None)
class DevicePathHypothesis(Hypothesis):
"""
Discover the device assuming the identifier is a device path.
"""
@classmethod
def match(cls, value):
"""
Match ``value`` under the assumption that it is a device path.
:returns: the device path or None
:rtype: str or NoneType
"""
return value
@classmethod
def lookup(cls, context, key):
"""
Lookup by the path.
:param Context context: the context
:param str key: the device path
:returns: a list of matching devices
:rtype: frozenset of :class:`Device`
"""
res = wrap_exception(Devices.from_path)(context, key)
return frozenset((res,)) if res is not None else frozenset()
class DeviceNameHypothesis(Hypothesis):
"""
Discover the device assuming the input is a device name.
Try every available subsystem.
"""
@classmethod
def find_subsystems(cls, context):
"""
Find all subsystems in sysfs.
:param Context context: the context
:rtype: frozenset
:returns: subsystems in sysfs
"""
sys_path = context.sys_path
dirnames = ("bus", "class", "subsystem")
absnames = (os.path.join(sys_path, name) for name in dirnames)
realnames = (d for d in absnames if os.path.isdir(d))
return frozenset(n for d in realnames for n in os.listdir(d))
@classmethod
def match(cls, value):
"""
Match ``value`` under the assumption that it is a device name.
:returns: the device path or None
:rtype: str or NoneType
"""
return value
@classmethod
def lookup(cls, context, key):
"""
Lookup by the path.
:param Context context: the context
:param str key: the device path
:returns: a list of matching devices
:rtype: frozenset of :class:`Device`
"""
func = wrap_exception(Devices.from_name)
res = (func(context, s, key) for s in cls.find_subsystems(context))
return frozenset(r for r in res if r is not None)
class DeviceFileHypothesis(Hypothesis):
"""
Discover the device assuming the value is some portion of a device file.
The device file may be a link to a device node.
"""
_LINK_DIRS = [
"/dev",
"/dev/disk/by-id",
"/dev/disk/by-label",
"/dev/disk/by-partlabel",
"/dev/disk/by-partuuid",
"/dev/disk/by-path",
"/dev/disk/by-uuid",
"/dev/input/by-path",
"/dev/mapper",
"/dev/md",
"/dev/vg",
]
@classmethod
def get_link_dirs(cls, context):
"""
Get all directories that may contain links to device nodes.
This method checks the device links of every device, so it is very
expensive.
:param Context context: the context
:returns: a sorted list of directories that contain device links
:rtype: list
"""
devices = context.list_devices()
devices_with_links = (d for d in devices if list(d.device_links))
links = (l for d in devices_with_links for l in d.device_links)
return sorted(set(os.path.dirname(l) for l in links))
@classmethod
def setup(cls, context):
"""
Set the link directories to be used when discovering by file.
Uses `get_link_dirs`, so is as expensive as it is.
:param Context context: the context
"""
cls._LINK_DIRS = cls.get_link_dirs(context)
@classmethod
def match(cls, value):
return value
@classmethod
def lookup(cls, context, key):
"""
Lookup the device under the assumption that the key is part of
the name of a device file.
:param Context context: the context
:param str key: a portion of the device file name
It is assumed that either it is the whole name of the device file
or it is the basename.
A device file may be a device node or a device link.
"""
func = wrap_exception(Devices.from_device_file)
if "/" in key:
device = func(context, key)
return frozenset((device,)) if device is not None else frozenset()
files = (os.path.join(ld, key) for ld in cls._LINK_DIRS)
devices = (func(context, f) for f in files)
return frozenset(d for d in devices if d is not None)
class Discovery:
# pylint: disable=too-few-public-methods
"""
Provides discovery methods for devices.
"""
_HYPOTHESES = [
DeviceFileHypothesis,
DeviceNameHypothesis,
DeviceNumberHypothesis,
DevicePathHypothesis,
]
def __init__(self):
self._hypotheses = self._HYPOTHESES
def setup(self, context):
"""
Set up individual hypotheses.
May be an expensive call.
:param Context context: the context
"""
for hyp in self._hypotheses:
hyp.setup(context)
def get_devices(self, context, value):
"""
Get the devices corresponding to value.
:param Context context: the context
:param str value: some identifier of the device
:returns: a list of corresponding devices
:rtype: frozenset of :class:`Device`
"""
return frozenset(
d for h in self._hypotheses for d in h.get_devices(context, value)
)
@@ -0,0 +1,198 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""pyudev.glib
===========
Glib integration.
:class:`MonitorObserver` integrates device monitoring into the Glib
mainloop by turing device events into Glib signals.
:mod:`gi.repository.GLib` and :mod:`gi.repository.GObject` from PyGObject_
must be available when importing this module. PyGtk is not required.
.. _PyGObject: http://www.pygtk.org/
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
.. versionadded:: 0.7
"""
# isort: THIRDPARTY
from gi.repository import GLib, GObject # pylint: disable=import-error
class _ObserverMixin:
"""Mixin to provide observer behavior to the old and the new API."""
# pylint: disable=too-few-public-methods
def _setup_observer(self, monitor):
# pylint: disable=attribute-defined-outside-init
self.monitor = monitor
self.event_source = None
self.enabled = True
@property
def enabled(self):
"""
Whether this observer is enabled or not.
If ``True`` (the default), this observer is enabled, and emits events.
Otherwise it is disabled and does not emit any events.
.. versionadded:: 0.14
"""
return self.event_source is not None
@enabled.setter
def enabled(self, value):
if value and self.event_source is None:
# pylint: disable=attribute-defined-outside-init
# pylint: disable=no-member
self.event_source = GLib.io_add_watch(
self.monitor,
GLib.PRIORITY_DEFAULT,
GLib.IO_IN,
self._process_udev_event,
)
elif not value and self.event_source is not None:
# pylint: disable=no-member
GLib.source_remove(self.event_source)
def _process_udev_event(self, source, condition):
# pylint: disable=unused-argument
# pylint: disable=no-member
if condition == GLib.IO_IN:
device = self.monitor.poll(timeout=0)
if device is not None:
self._emit_event(device)
return True
def _emit_event(self, device):
self.emit("device-event", device)
class MonitorObserver(GObject.Object, _ObserverMixin):
# pylint: disable=too-few-public-methods
"""
An observer for device events integrating into the :mod:`gi.repository.GLib`
mainloop.
This class inherits :class:`~gi.repository.GObject.Object` to turn device
events into glib signals.
>>> from pyudev import Context, Monitor
>>> from pyudev.glib import MonitorObserver
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
>>> monitor.filter_by(subsystem='input')
>>> observer = MonitorObserver(monitor)
>>> def device_event(observer, device):
... print('event {0} on device {1}'.format(device.action, device))
>>> observer.connect('device-event', device_event)
>>> monitor.start()
This class is a child of :class:`gi.repository.GObject.Object`.
"""
__gsignals__ = {
# explicitly convert the signal to str, because glib expects the
# *native* string type of the corresponding python version as type of
# signal name, and str() is the name of the native string type of both
# python versions. We could also remove the "unicode_literals" import,
# but I don't want to make exceptions to the standard set of future
# imports used throughout pyudev for the sake of consistency.
str("device-event"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
}
def __init__(self, monitor):
GObject.Object.__init__(self)
self._setup_observer(monitor)
GObject.type_register(MonitorObserver)
class GUDevMonitorObserver(GObject.Object, _ObserverMixin):
# pylint: disable=too-few-public-methods
"""
An observer for device events integrating into the :mod:`gi.repository.GLib`
mainloop.
.. deprecated:: 0.17
Will be removed in 1.0. Use :class:`MonitorObserver` instead.
"""
_action_signal_map = {
"add": "device-added",
"remove": "device-removed",
"change": "device-changed",
"move": "device-moved",
}
__gsignals__ = {
str("device-event"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_STRING, GObject.TYPE_PYOBJECT),
),
str("device-added"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
str("device-removed"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
str("device-changed"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
str("device-moved"): (
GObject.SIGNAL_RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT,),
),
}
def __init__(self, monitor):
GObject.Object.__init__(self)
self._setup_observer(monitor)
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use pyudev.glib.MonitorObserver instead.",
DeprecationWarning,
)
def _emit_event(self, device):
self.emit("device-event", device.action, device)
signal = self._action_signal_map.get(device.action)
if signal is not None:
self.emit(signal, device)
GObject.type_register(GUDevMonitorObserver)
@@ -0,0 +1,598 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.monitor
==============
Monitor implementation.
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: STDLIB
import errno
import os
from functools import partial
from threading import Thread
# isort: LOCAL
from pyudev._os import pipe, poll
from pyudev._util import eintr_retry_call, ensure_byte_string
from pyudev.device import Device
class Monitor:
"""
A synchronous device event monitor.
A :class:`Monitor` objects connects to the udev daemon and listens for
changes to the device list. A monitor is created by connecting to the
kernel daemon through netlink (see :meth:`from_netlink`):
>>> from pyudev import Context, Monitor
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
Once the monitor is created, you can add a filter using :meth:`filter_by()`
or :meth:`filter_by_tag()` to drop incoming events in subsystems, which are
not of interest to the application:
>>> monitor.filter_by('input')
When the monitor is eventually set up, you can either poll for events
synchronously:
>>> device = monitor.poll(timeout=3)
>>> if device:
... print('{0.action}: {0}'.format(device))
...
Or you can monitor events asynchronously with :class:`MonitorObserver`.
To integrate into various event processing frameworks, the monitor provides
a :func:`selectable <select.select>` file description by :meth:`fileno()`.
However, do *not* read or write directly on this file descriptor.
Instances of this class can directly be given as ``udev_monitor *`` to
functions wrapped through :mod:`ctypes`.
.. versionchanged:: 0.16
Remove :meth:`from_socket()` which is deprecated, and even removed in
recent udev versions.
"""
def __init__(self, context, monitor_p):
self.context = context
self._as_parameter_ = monitor_p
self._libudev = context._libudev
self._started = False
def __del__(self):
self._libudev.udev_monitor_unref(self)
@classmethod
def from_netlink(cls, context, source="udev"):
"""
Create a monitor by connecting to the kernel daemon through netlink.
``context`` is the :class:`Context` to use. ``source`` is a string,
describing the event source. Two sources are available:
``'udev'`` (the default)
Events emitted after udev as registered and configured the device.
This is the absolutely recommended source for applications.
``'kernel'``
Events emitted directly after the kernel has seen the device. The
device has not yet been configured by udev and might not be usable
at all. **Never** use this, unless you know what you are doing.
Return a new :class:`Monitor` object, which is connected to the
given source. Raise :exc:`~exceptions.ValueError`, if an invalid
source has been specified. Raise
:exc:`~exceptions.EnvironmentError`, if the creation of the monitor
failed.
"""
if source not in ("kernel", "udev"):
raise ValueError(
f'Invalid source: {source!r}. Must be one of "udev" or "kernel"'
)
monitor = context._libudev.udev_monitor_new_from_netlink( # pylint: disable=protected-access
context, ensure_byte_string(source)
)
if not monitor:
raise EnvironmentError("Could not create udev monitor")
return cls(context, monitor)
@property
def started(self):
"""
``True``, if this monitor was started, ``False`` otherwise. Readonly.
.. seealso:: :meth:`start()`
.. versionadded:: 0.16
"""
return self._started
def fileno(self):
"""
Return the file description associated with this monitor as integer.
This is really a real file descriptor ;), which can be watched and
:func:`select.select`\\ ed.
"""
return self._libudev.udev_monitor_get_fd(self)
def filter_by(self, subsystem, device_type=None):
"""
Filter incoming events.
``subsystem`` is a byte or unicode string with the name of a
subsystem (e.g. ``'input'``). Only events originating from the
given subsystem pass the filter and are handed to the caller.
If given, ``device_type`` is a byte or unicode string specifying the
device type. Only devices with the given device type are propagated
to the caller. If ``device_type`` is not given, no additional
filter for a specific device type is installed.
These filters are executed inside the kernel, and client processes
will usually not be woken up for device, that do not match these
filters.
.. versionchanged:: 0.15
This method can also be after :meth:`start()` now.
"""
subsystem = ensure_byte_string(subsystem)
if device_type is not None:
device_type = ensure_byte_string(device_type)
self._libudev.udev_monitor_filter_add_match_subsystem_devtype(
self, subsystem, device_type
)
self._libudev.udev_monitor_filter_update(self)
def filter_by_tag(self, tag):
"""
Filter incoming events by the given ``tag``.
``tag`` is a byte or unicode string with the name of a tag. Only
events for devices which have this tag attached pass the filter and are
handed to the caller.
Like with :meth:`filter_by` this filter is also executed inside the
kernel, so that client processes are usually not woken up for devices
without the given ``tag``.
.. udevversion:: 154
.. versionadded:: 0.9
.. versionchanged:: 0.15
This method can also be after :meth:`start()` now.
"""
self._libudev.udev_monitor_filter_add_match_tag(self, ensure_byte_string(tag))
self._libudev.udev_monitor_filter_update(self)
def remove_filter(self):
"""
Remove any filters installed with :meth:`filter_by()` or
:meth:`filter_by_tag()` from this monitor.
.. warning::
Up to udev 181 (and possibly even later versions) the underlying
``udev_monitor_filter_remove()`` seems to be broken. If used with
affected versions this method always raises
:exc:`~exceptions.ValueError`.
Raise :exc:`~exceptions.EnvironmentError` if removal of installed
filters failed.
.. versionadded:: 0.15
"""
self._libudev.udev_monitor_filter_remove(self)
self._libudev.udev_monitor_filter_update(self)
def enable_receiving(self):
"""
Switch the monitor into listing mode.
Connect to the event source and receive incoming events. Only after
calling this method, the monitor listens for incoming events.
.. note::
This method is implicitly called by :meth:`__iter__`. You don't
need to call it explicitly, if you are iterating over the
monitor.
.. deprecated:: 0.16
Will be removed in 1.0. Use :meth:`start()` instead.
"""
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use Monitor.start() instead.", DeprecationWarning
)
self.start()
def start(self):
"""
Start this monitor.
The monitor will not receive events until this method is called. This
method does nothing if called on an already started :class:`Monitor`.
.. note::
Typically you don't need to call this method. It is implicitly
called by :meth:`poll()` and :meth:`__iter__()`.
.. seealso:: :attr:`started`
.. versionchanged:: 0.16
This method does nothing if the :class:`Monitor` was already
started.
"""
if not self._started:
self._libudev.udev_monitor_enable_receiving(self)
# Force monitor FD into non-blocking mode
pipe.set_fd_status_flag(self, os.O_NONBLOCK)
self._started = True
def set_receive_buffer_size(self, size):
"""
Set the receive buffer ``size``.
``size`` is the requested buffer size in bytes, as integer.
.. note::
The CAP_NET_ADMIN capability must be contained in the effective
capability set of the caller for this method to succeed. Otherwise
:exc:`~exceptions.EnvironmentError` will be raised, with ``errno``
set to :data:`~errno.EPERM`. Unprivileged processes typically lack
this capability. You can check the capabilities of the current
process with the python-prctl_ module:
>>> import prctl
>>> prctl.cap_effective.net_admin
Raise :exc:`~exceptions.EnvironmentError`, if the buffer size could not
bet set.
.. versionadded:: 0.13
.. _python-prctl: http://packages.python.org/python-prctl
"""
self._libudev.udev_monitor_set_receive_buffer_size(self, size)
def _receive_device(self):
"""Receive a single device from the monitor.
Return the received :class:`Device`, or ``None`` if no device could be
received.
"""
while True:
try:
device_p = self._libudev.udev_monitor_receive_device(self)
return Device(self.context, device_p) if device_p else None
except EnvironmentError as error:
if error.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
# No data available
return None
if error.errno == errno.EINTR:
# Try again if our system call was interrupted
continue
raise
def poll(self, timeout=None):
"""
Poll for a device event.
You can use this method together with :func:`iter()` to synchronously
monitor events in the current thread::
for device in iter(monitor.poll, None):
print('{0.action} on {0.device_path}'.format(device))
Since this method will never return ``None`` if no ``timeout`` is
specified, this is effectively an endless loop. With
:func:`functools.partial()` you can also create a loop that only waits
for a specified time::
for device in iter(partial(monitor.poll, 3), None):
print('{0.action} on {0.device_path}'.format(device))
This loop will only wait three seconds for a new device event. If no
device event occurred after three seconds, the loop will exit.
``timeout`` is a floating point number that specifies a time-out in
seconds. If omitted or ``None``, this method blocks until a device
event is available. If ``0``, this method just polls and will never
block.
.. note::
This method implicitly calls :meth:`start()`.
Return the received :class:`Device`, or ``None`` if a timeout
occurred. Raise :exc:`~exceptions.EnvironmentError` if event retrieval
failed.
.. seealso::
:attr:`Device.action`
The action that created this event.
:attr:`Device.sequence_number`
The sequence number of this event.
.. versionadded:: 0.16
"""
if timeout is not None and timeout > 0:
# .poll() takes timeout in milliseconds
timeout = int(timeout * 1000)
self.start()
if eintr_retry_call(poll.Poll.for_events((self, "r")).poll, timeout):
return self._receive_device()
return None
def receive_device(self):
"""
Receive a single device from the monitor.
.. warning::
You *must* call :meth:`start()` before calling this method.
The caller must make sure, that there are events available in the
event queue. The call blocks, until a device is available.
If a device was available, return ``(action, device)``. ``device``
is the :class:`Device` object describing the device. ``action`` is
a string describing the action. Usual actions are:
``'add'``
A device has been added (e.g. a USB device was plugged in)
``'remove'``
A device has been removed (e.g. a USB device was unplugged)
``'change'``
Something about the device changed (e.g. a device property)
``'online'``
The device is online now
``'offline'``
The device is offline now
Raise :exc:`~exceptions.EnvironmentError`, if no device could be
read.
.. deprecated:: 0.16
Will be removed in 1.0. Use :meth:`Monitor.poll()` instead.
"""
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use Monitor.poll() instead.", DeprecationWarning
)
device = self.poll()
return device.action, device
def __iter__(self):
"""
Wait for incoming events and receive them upon arrival.
This methods implicitly calls :meth:`start()`, and starts polling the
:meth:`fileno` of this monitor. If a event comes in, it receives the
corresponding device and yields it to the caller.
The returned iterator is endless, and continues receiving devices
without ever stopping.
Yields ``(action, device)`` (see :meth:`receive_device` for a
description).
.. deprecated:: 0.16
Will be removed in 1.0. Use an explicit loop over :meth:`poll()`
instead, or monitor asynchronously with :class:`MonitorObserver`.
"""
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use an explicit loop over "
'"poll()" instead, or monitor asynchronously with '
'"MonitorObserver".',
DeprecationWarning,
)
self.start()
while True:
device = self.poll()
if device is not None:
yield device.action, device
class MonitorObserver(Thread):
"""
An asynchronous observer for device events.
This class subclasses :class:`~threading.Thread` class to asynchronously
observe a :class:`Monitor` in a background thread:
>>> from pyudev import Context, Monitor, MonitorObserver
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
>>> monitor.filter_by(subsystem='input')
>>> def print_device_event(device):
... print('background event {0.action}: {0.device_path}'.format(device))
>>> observer = MonitorObserver(monitor, callback=print_device_event, name='monitor-observer')
>>> observer.daemon
True
>>> observer.start()
In the above example, input device events will be printed in background,
until :meth:`stop()` is called on ``observer``.
.. note::
Instances of this class are always created as daemon thread. If you do
not want to use daemon threads for monitoring, you need explicitly set
:attr:`~threading.Thread.daemon` to ``False`` before invoking
:meth:`~threading.Thread.start()`.
.. seealso::
:attr:`Device.action`
The action that created this event.
:attr:`Device.sequence_number`
The sequence number of this event.
.. versionadded:: 0.14
.. versionchanged:: 0.15
:meth:`Monitor.start()` is implicitly called when the thread is started.
"""
def __init__(
self, monitor, event_handler=None, callback=None, *args, **kwargs
): # pylint: disable=keyword-arg-before-vararg
"""
Create a new observer for the given ``monitor``.
``monitor`` is the :class:`Monitor` to observe. ``callback`` is the
callable to invoke on events, with the signature ``callback(device)``
where ``device`` is the :class:`Device` that caused the event.
.. warning::
``callback`` is invoked in the observer thread, hence the observer
is blocked while callback executes.
``args`` and ``kwargs`` are passed unchanged to the constructor of
:class:`~threading.Thread`.
.. deprecated:: 0.16
The ``event_handler`` argument will be removed in 1.0. Use
the ``callback`` argument instead.
.. versionchanged:: 0.16
Add ``callback`` argument.
"""
if callback is None and event_handler is None:
raise ValueError("callback missing")
if callback is not None and event_handler is not None:
raise ValueError("Use either callback or event handler")
Thread.__init__(self, *args, **kwargs)
self.monitor = monitor
# observer threads should not keep the interpreter alive
self.daemon = True
self._stop_event = None
if event_handler is not None:
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
'"event_handler" argument will be removed in 1.0. '
"Use Monitor.poll() instead.",
DeprecationWarning,
)
callback = lambda d: event_handler( # pylint: disable=unnecessary-lambda-assignment
d.action, d
)
self._callback = callback
def start(self):
"""Start the observer thread."""
if not self.is_alive():
self._stop_event = pipe.Pipe.open()
Thread.start(self)
def run(self):
self.monitor.start()
notifier = poll.Poll.for_events(
(self.monitor, "r"), (self._stop_event.source, "r")
)
while True:
for file_descriptor, event in eintr_retry_call(notifier.poll):
if file_descriptor == self._stop_event.source.fileno():
# in case of a stop event, close our pipe side, and
# return from the thread
self._stop_event.source.close()
return
if file_descriptor == self.monitor.fileno() and event == "r":
read_device = partial(
eintr_retry_call, self.monitor.poll, timeout=0
)
for device in iter(read_device, None):
self._callback(device)
else:
raise EnvironmentError("Observed monitor hung up")
def send_stop(self):
"""
Send a stop signal to the background thread.
The background thread will eventually exit, but it may still be running
when this method returns. This method is essentially the asynchronous
equivalent to :meth:`stop()`.
.. note::
The underlying :attr:`monitor` is *not* stopped.
"""
if self._stop_event is None:
return
with self._stop_event.sink:
# emit a stop event to the thread
eintr_retry_call(self._stop_event.sink.write, b"\x01")
self._stop_event.sink.flush()
def stop(self):
"""
Synchronously stop the background thread.
.. note::
This method can safely be called from the observer thread. In this
case it is equivalent to :meth:`send_stop()`.
Send a stop signal to the backgroud (see :meth:`send_stop`), and waits
for the background thread to exit (see :meth:`~threading.Thread.join`)
if the current thread is *not* the observer thread.
After this method returns in a thread *that is not the observer
thread*, the ``callback`` is guaranteed to not be invoked again
anymore.
.. note::
The underlying :attr:`monitor` is *not* stopped.
.. versionchanged:: 0.16
This method can be called from the observer thread.
"""
self.send_stop()
try:
self.join()
except RuntimeError:
pass
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.pyqt4
============
PyQt4 integration.
:class:`MonitorObserver` integrates device monitoring into the PyQt4\\_
mainloop by turning device events into Qt signals.
:mod:`PyQt4.QtCore` from PyQt4\\_ must be available when importing this
module.
.. _PyQt4: http://riverbankcomputing.co.uk/software/pyqt/intro
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""
# isort: THIRDPARTY
from PyQt4 import QtCore # pylint: disable=import-error
from ._qt_base import MonitorObserverGenerator, QUDevMonitorObserverGenerator
# pylint: disable=invalid-name
MonitorObserver = MonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.pyqtSignal, QtCore.QSocketNotifier
)
"""
.. deprecated:: 0.17
Will be removed in 1.0. Use :class:`MonitorObserver` instead.
"""
QUDevMonitorObserver = QUDevMonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.pyqtSignal, QtCore.QSocketNotifier
)
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.pyqt5
============
PyQt5 integration.
:class:`MonitorObserver` integrates device monitoring into the PyQt5_
mainloop by turning device events into Qt signals.
:mod:`PyQt5.QtCore` from PyQt5_ must be available when importing this
module.
.. _gPyQt5: http://riverbankcomputing.co.uk/software/pyqt/intro
.. moduleauthor:: Tobias Gehring <mail@tobiasgehring.de>
"""
# isort: THIRDPARTY
from PyQt5 import QtCore # pylint: disable=import-error
from ._qt_base import MonitorObserverGenerator
# pylint: disable=invalid-name
MonitorObserver = MonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.pyqtSignal, QtCore.QSocketNotifier
)
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.pyside
=============
PySide integration.
:class:`QUDevMonitorObserver` integrates device monitoring into the
PySide\\_ mainloop by turing device events into Qt signals.
:mod:`PySide.QtCore` from PySide\\_ must be available when importing this
module.
.. _PySide: http://www.pyside.org
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
.. versionadded:: 0.6
"""
# isort: THIRDPARTY
from PySide import QtCore # pylint: disable=import-error
from ._qt_base import MonitorObserverGenerator, QUDevMonitorObserverGenerator
# pylint: disable=invalid-name
MonitorObserver = MonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.Signal, QtCore.QSocketNotifier
)
"""
.. deprecated:: 0.17
Will be removed in 1.0. Use :class:`MonitorObserver` instead.
"""
QUDevMonitorObserver = QUDevMonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.Signal, QtCore.QSocketNotifier
)
@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.pyside
=============
PySide integration.
:class:`QUDevMonitorObserver` integrates device monitoring into the
PySide\\_ mainloop by turing device events into Qt signals.
:mod:`PySide.QtCore` from PySide\\_ must be available when importing this
module.
.. _PySide: http://www.pyside.org
.. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
.. versionadded:: 0.6
"""
# isort: THIRDPARTY
from PySide6 import QtCore # pylint: disable=import-error
from ._qt_base import MonitorObserverGenerator
# pylint: disable=invalid-name
MonitorObserver = MonitorObserverGenerator.make_monitor_observer(
QtCore.QObject, QtCore.Signal, QtCore.QSocketNotifier
)
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
pyudev.version
==============
Version information.
.. moduleauthor:: mulhern <amulhern@redhat.com>
"""
__version_info__ = (0, 24, 4, "")
__version__ = (
f'{".".join(str(x) for x in __version_info__[:3])}'
f'{"".join(str(x) for x in __version_info__[3:])}'
)
@@ -0,0 +1,149 @@
# -*- coding: utf-8 -*-
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""pyudev.wx
=========
Wx integration.
:class:`MonitorObserver` integrates device monitoring into the wxPython\\_
mainloop by turing device events into wx events.
:mod:`wx` from wxPython\\_ must be available when importing this module.
.. _wxPython: http://wxpython.org/
.. moduleauthor:: Tobias Eberle <tobias.eberle@gmx.de>
.. versionadded:: 0.14
"""
# isort: THIRDPARTY
from wx import EvtHandler, PostEvent # pylint: disable=import-error
from wx.lib.newevent import NewEvent # pylint: disable=import-error, no-name-in-module
# isort: LOCAL
# for some reason, pylint thinks pyudev is a third party import
import pyudev # pylint: disable=wrong-import-order
DeviceEvent, EVT_DEVICE_EVENT = NewEvent() # pylint: disable=invalid-name
class MonitorObserver(EvtHandler):
"""
An observer for device events integrating into the :mod:`wx` mainloop.
This class inherits :class:`~wx.EvtHandler` to turn device events into
wx events:
>>> from pyudev import Context, Monitor
>>> from pyudev.wx import MonitorObserver
>>> context = Context()
>>> monitor = Monitor.from_netlink(context)
>>> monitor.filter_by(subsystem='input')
>>> observer = MonitorObserver(monitor)
>>> def device_event(event):
... print('action {0} on device {1}'.format(event.device.action, event.device))
>>> observer.Bind(EVT_DEVICE_EVENT, device_event)
>>> monitor.start()
This class is a child of :class:`wx.EvtHandler`.
.. versionadded:: 0.17
"""
def __init__(self, monitor):
EvtHandler.__init__(self)
self.monitor = monitor
self._observer_thread = None
self.start()
@property
def enabled(self):
"""
Whether this observer is enabled or not.
If ``True`` (the default), this observer is enabled, and emits events.
Otherwise it is disabled and does not emit any events.
"""
return self._observer_thread is not None
@enabled.setter
def enabled(self, value):
if value:
self.start()
else:
self.stop()
def start(self):
"""
Enable this observer.
Do nothing, if the observer is already enabled.
"""
if self._observer_thread is not None:
return
self._observer_thread = pyudev.MonitorObserver(
self.monitor, callback=self._emit_event, name="wx-observer-thread"
)
self._observer_thread.start()
def stop(self):
"""
Disable this observer.
Do nothing, if the observer is already disabled.
"""
if self._observer_thread is None:
return
self._observer_thread.stop()
def _emit_event(self, device):
PostEvent(self, DeviceEvent(device=device))
DeviceAddedEvent, EVT_DEVICE_ADDED = NewEvent() # pylint: disable=invalid-name
DeviceRemovedEvent, EVT_DEVICE_REMOVED = NewEvent() # pylint: disable=invalid-name
DeviceChangedEvent, EVT_DEVICE_CHANGED = NewEvent() # pylint: disable=invalid-name
DeviceMovedEvent, EVT_DEVICE_MOVED = NewEvent() # pylint: disable=invalid-name
class WxUDevMonitorObserver(MonitorObserver):
"""An observer for device events integrating into the :mod:`wx` mainloop.
.. deprecated:: 0.17
Will be removed in 1.0. Use :class:`MonitorObserver` instead.
"""
_action_event_map = {
"add": DeviceAddedEvent,
"remove": DeviceRemovedEvent,
"change": DeviceChangedEvent,
"move": DeviceMovedEvent,
}
def __init__(self, monitor):
MonitorObserver.__init__(self, monitor)
# isort: STDLIB
import warnings # pylint: disable=import-outside-toplevel
warnings.warn(
"Will be removed in 1.0. Use pyudev.wx.MonitorObserver instead.",
DeprecationWarning,
)
def _emit_event(self, device):
PostEvent(self, DeviceEvent(action=device.action, device=device))
event_class = self._action_event_map.get(device.action)
if event_class is not None:
PostEvent(self, event_class(device=device))