pyudev - libudev binding¶
A binding to libudev.
The Context provides the connection to the udev device database
and enumerates devices. Individual devices are represented by the
Device class.
Device monitoring is provided by Monitor and
MonitorObserver. With pyudev.pyqt4, pyudev.pyside,
pyudev.glib and pyudev.wx device monitoring can be integrated
into the event loop of various GUI toolkits.
A device database connection. |
|
A single device with attached attributes and properties. |
|
Class for constructing |
|
A synchronous device event monitor. |
|
An asynchronous observer for device events. |
Version information¶
-
pyudev.__version__¶ The version of
pyudevas string. This string contains a major and a minor version number, and optionally a revision in the formmajor.minor.revision. As said, therevisionpart is optional and may not be present.This attribute is mainly intended for display purposes, use
__version_info__to check the version ofpyudevin source code.
-
pyudev.__version_info__¶ The version of
pyudevas tuple of integers. This tuple contains a major and a minor number, and optionally a revision number in the form(major, minor, revision). As said, therevisioncomponent is optional and may not be present.New in version 0.10.
-
pyudev.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
sys.version_info).As libudev itself does not provide a function to query the version number, this function calls the
udevadmutility, so be prepared to catchEnvironmentErrorandCalledProcessErrorif you call this function.Return the version number as single integer. Raise
ValueError, if the version number retrieved from udev could not be converted to an integer. RaiseEnvironmentError, ifudevadmwas not found, or could not be executed. Raisesubprocess.CalledProcessError, ifudevadmreturned a non-zero exit code. On Python 2.7 or newer, theoutputattribute of this exception is correctly set.New in version 0.8.
Context – UDev database context¶
-
class
pyudev.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.
sys_path,device_path), and provides device enumeration (list_devices()).Instances of this class can directly be given as
udev *to functions wrapped throughctypes.-
__init__()¶ Create a new context.
-
sys_path¶ The
sysfsmount point defaulting to/sys'as unicode string.
-
device_path¶ The device directory path defaulting to
/devas unicode string.
-
run_path¶ The run runtime directory path defaulting to
/runas unicode string.Required udev version: 167
New in version 0.10.
-
log_priority¶ The logging priority of the interal logging facitility of udev as integer with a standard
syslogpriority. Assign to this property to change the logging priority.UDev uses the standard
syslogpriorities. Constants for these priorities are defined in thesyslogmodule in the standard library:>>> import syslog >>> context = pyudev.Context() >>> context.log_priority = syslog.LOG_DEBUG
New in version 0.9.
-
list_devices(**kwargs)¶ List all available devices.
The arguments of this method are the same as for
Enumerator.match(). In fact, the arguments are simply passed straight to methodmatch().This function creates and returns an
Enumeratorobject, that can be used to filter the list of devices, and eventually retrieveDeviceobjects representing matching devices.Changed in version 0.8: Accept keyword arguments now for easy matching.
-
Enumerator – device enumeration and filtering¶
-
class
pyudev.Enumerator¶ A filtered iterable of devices.
To retrieve devices, simply iterate over an instance of this class. This operation yields
Deviceobjects representing the available devices.Before iteration the device list can be filtered by subsystem or by property values using
match_subsystem()andmatch_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 throughctypes.-
match(**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
subsystemis forwarded tomatch_subsystem().The value for the keyword argument
sys_nameis forwared tomatch_sys_name().The value for the keyword argument
tagis forwared tomatch_tag().The value for the keyword argument
parentis forwared tomatch_parent().All other keyword arguments are forwareded one by one to
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.
New in version 0.8.
Changed in version 0.13: Add
parentkeyword.
-
match_subsystem(subsystem, nomatch=False)¶ Include all devices, which are part of the given
subsystem.subsystemis either a unicode string or a byte string, containing the name of the subsystem. IfnomatchisTrue(default isFalse), the match is inverted: A device is only included if it is not part of the givensubsystem.Note that, if a device has no subsystem, it is not included either with value of
nomatchTrue or with value ofnomatchFalse.Return the instance again.
-
match_sys_name(sys_name)¶ Include all devices with the given name.
sys_nameis a byte or unicode string containing the device name.Return the instance again.
New in version 0.8.
-
match_property(prop, value)¶ Include all devices, whose
prophas the givenvalue.propis either a unicode string or a byte string, containing the name of the property to match.valueis a property value, being one of the following types:int()bool()A byte string
Anything convertable to a unicode string (including a unicode string itself)
Return the instance again.
-
match_attribute(attribute, value, nomatch=False)¶ Include all devices, whose
attributehas the givenvalue.attributeis either a unicode string or a byte string, containing the name of a sys attribute to match.valueis an attribute value, being one of the following types:int(),bool()A byte string
Anything convertable to a unicode string (including a unicode string itself)
If
nomatchisTrue(default isFalse), the match is inverted: A device is include if theattributedoes not match the givenvalue.Note
If
nomatchisTrue, devices which do not have the givenattributeat all are also included. In other words, withnomatch=Truethe givenattributeis not guaranteed to exist on all returned devices.Return the instance again.
-
match_tag(tag)¶ Include all devices, which have the given
tagattached.tagis a byte or unicode string containing the tag name.Return the instance again.
Required udev version: 154
New in version 0.6.
-
match_parent(parent)¶ Include all devices on the subtree of the given
parentdevice.The
parentdevice itself is also included.parentis aDevice.Return the instance again.
Required udev version: 172
New in version 0.13.
-
match_is_initialized()¶ 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.
See also
Required udev version: 165
New in version 0.8.
-
Devices – constructing Device objects¶
-
class
pyudev.Devices¶ Class for constructing
Deviceobjects from various kinds of data.Construction of device objects
-
classmethod
from_path(context, path)¶ Create a device from a device
path. Thepathmay or may not start with thesysfsmount point:>>> from pyudev import Context, Device >>> context = Context() >>> Devices.from_path(context, '/devices/platform') Device(u'/sys/devices/platform') >>> Devices.from_path(context, '/sys/devices/platform') Device(u'/sys/devices/platform')
contextis theContextin which to search the device.pathis a device path as unicode or byte string.Return a
Deviceobject for the device. RaiseDeviceNotFoundAtPathError, if no device was found forpath.New in version 0.18.
-
classmethod
from_sys_path(context, sys_path)¶ Create a new device from a given
sys_path:>>> from pyudev import Context, Device >>> context = Context() >>> Devices.from_sys_path(context, '/sys/devices/platform') Device(u'/sys/devices/platform')
contextis theContextin which to search the device.sys_pathis a unicode or byte string containing the path of the device insidesysfswith the mount point included.Return a
Deviceobject for the device. RaiseDeviceNotFoundAtPathError, if no device was found forsys_path.New in version 0.18.
-
classmethod
from_name(context, subsystem, sys_name)¶ Create a new device from a given
subsystemand a givensys_name:>>> from pyudev import Context, Device >>> context = Context() >>> sda = Devices.from_name(context, 'block', 'sda') >>> sda Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda') >>> sda == Devices.from_path(context, '/block/sda')
contextis theContextin which to search the device.subsystemandsys_nameare byte or unicode strings, which denote the subsystem and the name of the device to create.Return a
Deviceobject for the device. RaiseDeviceNotFoundByNameError, if no device was found with the given name.New in version 0.18.
-
classmethod
from_device_number(context, typ, number)¶ Create a new device from a device
numberwith the given devicetype:>>> import os >>> from pyudev import Context, Device >>> ctx = Context() >>> major, minor = 8, 0 >>> device = Devices.from_device_number(context, 'block', ... os.makedev(major, minor)) >>> device Device(u'/sys/devices/pci0000:00/0000:00:11.0/host0/target0:0:0/0:0:0:0/block/sda') >>> os.major(device.device_number), os.minor(device.device_number) (8, 0)
Use
os.makedev()to construct a device number from a major and a minor device number, as shown in the example above.Warning
Device numbers are not unique across different device types. Passing a correct number with a wrong type may silently yield a wrong device object, so make sure to pass the correct device type.
contextis theContext, in which to search the device.typeis either'char'or'block', according to whether the device is a character or block device.numberis the device number as integer.Return a
Deviceobject for the device with the given devicenumber. RaiseDeviceNotFoundByNumberError, if no device was found with the given device type and number.New in version 0.18.
-
classmethod
from_device_file(context, filename)¶ Create a new device from the given device file:
>>> from pyudev import Context, Device >>> context = Context() >>> device = Devices.from_device_file(context, '/dev/sda') >>> device Device(u'/sys/devices/pci0000:00/0000:00:0d.0/host2/target2:0:0/2:0:0:0/block/sda') >>> device.device_node u'/dev/sda'
Warning
Though the example seems to suggest that
device.device_node == filenameholds withdevice = Devices.from_device_file(context, filename), this is only true in a majority of cases. There can be devices, for which this relation is actually false! Thus, do not expectdevice_nodeto be equal to the givenfilenamefor the returnedDevice. Especially, usedevice_nodeif you need the device file of aDevicecreated with this method afterwards.contextis theContextin which to search the device.filenameis a string containing the path of a device file.Return a
Devicerepresenting the given device file. RaiseDeviceNotFoundByFileErroriffilenameis no device file at all or iffilenamedoes not exist or if its metadata was inaccessible.New in version 0.18.
-
classmethod
from_environment(context)¶ Create a new device from the process environment (as in
os.environ).This only works reliable, if the current process is called from an udev rule, and is usually used for tools executed from
IMPORT=rules. Use this method to create device objects in Python scripts called from udev rules.contextis the libraryContext.Return a
Deviceobject constructed from the environment. RaiseDeviceNotFoundInEnvironmentError, if no device could be created from the environment.Required udev version: 152
New in version 0.18.
-
classmethod
Device – accessing device information¶
-
class
pyudev.Device¶ A single device with attached attributes and properties.
This class subclasses the
MappingABC, providing a read-only dictionary mapping property names to the corresponding values. Therefore all well-known dicitionary methods and operators (e.g..keys(),.items(),in) are available to access device properties.Aside of the properties, a device also has a set of udev-specific attributes like the path inside
sysfs.Deviceobjects compare equal and unequal to other devices and to strings (based ondevice_path). However, there is no ordering onDeviceobjects, and the corresponding operators>,<,<=and>=raiseTypeError.Warning
Never use object identity (
isoperator) to compareDeviceobjects.pyudevmay create multipleDeviceobjects for the same device. Instead compare devices by value using==or!=.Deviceobjects are hashable and can therefore be used as keys in dictionaries and sets.They can also be given directly as
udev_device *to functions wrapped throughctypes.Construction of device objects
-
classmethod
from_path(context, path)¶ New in version 0.4.
Deprecated since version 0.18: Use
Devices.from_pathinstead.
-
classmethod
from_sys_path(context, sys_path)¶ Changed in version 0.4: Raise
NoSuchDeviceErrorinstead of returningNone, if no device was found forsys_path.Changed in version 0.5: Raise
DeviceNotFoundAtPathErrorinstead ofNoSuchDeviceError.Deprecated since version 0.18: Use
Devices.from_sys_pathinstead.
-
classmethod
from_name(context, subsystem, sys_name)¶ New in version 0.5.
Deprecated since version 0.18: Use
Devices.from_nameinstead.
-
classmethod
from_device_number(context, typ, number)¶ New in version 0.11.
Deprecated since version 0.18: Use
Devices.from_device_numberinstead.
-
classmethod
from_device_file(context, filename)¶ New in version 0.15.
Deprecated since version 0.18: Use
Devices.from_device_fileinstead.
-
classmethod
from_environment(context)¶ New in version 0.6.
Deprecated since version 0.18: Use
Devices.from_environmentinstead.
General attributes
-
sys_path¶ Absolute path of this device in
sysfsincluding thesysfsmount point as unicode string.
-
sys_name¶ Device file name inside
sysfsas unicode string.
-
sys_number¶ The trailing number of the
sys_nameas unicode string, orNone, if the device has no trailing number in its name.Note
The number is returned as unicode string to preserve the exact format of the number, especially any leading zeros:
>>> from pyudev import Context, Device >>> context = Context() >>> device = Devices.from_path(context, '/sys/devices/LNXSYSTM:00') >>> device.sys_number u'00'
To work with numbers, explicitly convert them to ints:
>>> int(device.sys_number) 0
New in version 0.11.
-
device_path¶ Kernel device path as unicode string. This path uniquely identifies a single device.
Unlike
sys_path, this path does not contain thesysfsmount point. However, the path is absolute and starts with a slash'/'.
A
Tagsobject representing the tags attached to this device.The
Tagsobject supports a test for a single tag as well as iteration over all tags:>>> from pyudev import Context >>> context = Context() >>> device = next(iter(context.list_devices(tag='systemd'))) >>> 'systemd' in device.tags True >>> list(device.tags) [u'seat', u'systemd', u'uaccess']
Tags are arbitrary classifiers that can be attached to devices by udev scripts and daemons. For instance, systemd uses tags for multi-seat support.
Required udev version: 154
New in version 0.6.
Changed in version 0.13: Return a
Tagsobject now.
Device driver and subsystem
-
subsystem¶ Name of the subsystem this device is part of as unicode string.
- Returns
name of subsystem if found, else None
- Return type
unicode string or NoneType
-
driver¶ The driver name as unicode string, or
None, if there is no driver for this device.New in version 0.5.
-
device_type¶ Device type as unicode string, or
None, if the device type is unknown.>>> from pyudev import Context >>> context = Context() >>> for device in context.list_devices(subsystem='net'): ... '{0} - {1}'.format(device.sys_name, device.device_type or 'ethernet') ... u'eth0 - ethernet' u'wlan0 - wlan' u'lo - ethernet' u'vboxnet0 - ethernet'
New in version 0.10.
Device nodes
-
device_node¶ Absolute path to the device node of this device as unicode string or
None, if this device doesn’t have a device node. The path includes the device directory (seeContext.device_path).This path always points to the actual device node associated with this device, and never to any symbolic links to this device node. See
device_linksto get a list of symbolic links to this device node.Warning
For devices created with
from_device_file(), the value of this property is not necessary equal to thefilenamegiven tofrom_device_file().
-
device_number¶ The device number of the associated device as integer, or
0, if no device number is associated.Use
os.major()andos.minor()to decompose the device number into its major and minor number:>>> import os >>> from pyudev import Context, Device >>> context = Context() >>> sda = Devices.from_name(context, 'block', 'sda') >>> sda.device_number 2048L >>> (os.major(sda.device_number), os.minor(sda.device_number)) (8, 0)
For devices with an associated
device_node, this is the same as thest_rdevfield of the stat result of thedevice_node:>>> os.stat(sda.device_node).st_rdev 2048
New in version 0.11.
-
device_links¶ An iterator, which yields the absolute paths (including the device directory, see
Context.device_path) of all symbolic links pointing to thedevice_nodeof this device. The paths are unicode strings.UDev can create symlinks to the original device node (see
device_node) inside the device directory. This is often used to assign a constant, fixed device node to devices like removeable media, which technically do not have a constant device node, or to map a single device into multiple device hierarchies. The property provides access to all such symbolic links, which were created by UDev for this device.Warning
Links are not necessarily resolved by
Devices.from_device_file(). Hence do not rely onDevices.from_device_file(context, link).device_path == device.device_pathfrom anylinkindevice.device_links.
Device initialization time
-
is_initialized¶ True, if the device is initialized,Falseotherwise.A device is initialized, if udev has already handled this device and has set up device node permissions and context, or renamed a network device.
Consequently, this property is only implemented for devices with a device node or for network devices. On all other devices this property is always
True.It is not recommended, that you use uninitialized devices.
See also
Required udev version: 165
New in version 0.8.
-
time_since_initialized¶ The time elapsed since initialization as
timedelta.This property is only implemented on devices, which need to store properties in the udev database. On all other devices this property is simply zero
timedelta.See also
Required udev version: 165
New in version 0.8.
Device hierarchy
-
ancestors¶ Yield all ancestors of this device from bottom to top.
Return an iterator yielding a
Deviceobject for each ancestor of this device from bottom to top.New in version 0.16.
-
children¶ Yield all direct children of this device.
Note
In udev, parent-child relationships are generally ambiguous, i.e. a parent can have multiple children, and a child can have multiple parents. Hence, child.parent == parent does generally not hold for all child objects in parent.children. In other words, the
parentof a device in this property can be different from this device!Note
As the underlying library does not provide any means to directly query the children of a device, this property performs a linear search through all devices.
Return an iterable yielding a
Deviceobject for each direct child of this device.Required udev version: 172
Changed in version 0.13: Requires udev version 172 now.
-
find_parent(subsystem, device_type=None)¶ Find the parent device with the given
subsystemanddevice_type.subsystemis a byte or unicode string containing the name of the subsystem, in which to search for the parent.device_typeis a byte or unicode string holding the expected device type of the parent. It can beNone(the default), which means, that no specific device type is expected.Return a parent
Devicewithin the givensubsystemand, ifdevice_typeis notNone, with the givendevice_type, orNone, if this device has no parent device matching these constraints.New in version 0.9.
Device events
-
action¶ The device event action as string, or
None, if this device was not received from aMonitor.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
Warning
Though the actions listed above are the most common, this property may return other values, too, so be prepared to handle unknown actions!
New in version 0.16.
-
sequence_number¶ The device event sequence number as integer, or
0if this device has no sequence number, i.e. was not received from aMonitor.New in version 0.16.
Device properties
-
__iter__()¶ Iterate over the names of all properties defined for this device.
Return a generator yielding the names of all properties of this device as unicode strings.
Deprecated since version 0.21: Will be removed in 1.0. Access properties with Device.properties.
-
__len__()¶ Return the amount of properties defined for this device as integer.
Deprecated since version 0.21: Will be removed in 1.0. Access properties with Device.properties.
-
__getitem__(prop)¶ Get the given property from this device.
propis a unicode or byte string containing the name of the property.Return the property value as unicode string, or raise a
KeyError, if the given property is not defined for this device.Deprecated since version 0.21: Will be removed in 1.0. Access properties with Device.properties.
-
asint(prop)¶ Get the given property from this device as integer.
propis a unicode or byte string containing the name of the property.Return the property value as integer. Raise a
KeyError, if the given property is not defined for this device, or aValueError, if the property value cannot be converted to an integer.Deprecated since version 0.21: Will be removed in 1.0. Use Device.properties.asint() instead.
-
asbool(prop)¶ Get the given property from this device as boolean.
A boolean property has either a value of
'1'or of'0', where'1'stands forTrue, and'0'forFalse. Any other value causes aValueErrorto be raised.propis a unicode or byte string containing the name of the property.Return
True, if the property value is'1'andFalse, if the property value is'0'. Any other value raises aValueError. Raise aKeyError, if the given property is not defined for this device.Deprecated since version 0.21: Will be removed in 1.0. Use Device.properties.asbool() instead.
Sysfs attributes
-
attributes¶ The system attributes of this device as read-only
Attributesmapping.System attributes are basically normal files inside the the device directory. These files contain all sorts of information about the device, which may not be reflected by properties. These attributes are commonly used for matching in udev rules, and can be printed using
udevadm info --attribute-walk.The values of these attributes are not always proper strings, and can contain arbitrary bytes.
New in version 0.5.
Deprecated members
-
traverse()¶ Traverse all parent devices of this device from bottom to top.
Return an iterable yielding all parent devices as
Deviceobjects, not including the current device. The last yieldedDeviceis the top of the device hierarchy.Deprecated since version 0.16: Will be removed in 1.0. Use
ancestorsinstead.
-
classmethod
-
class
pyudev.Attributes¶ udev attributes for
Deviceobjects.New in version 0.5.
-
asstring(attribute)¶ Get the given
attributefor the device as unicode string.- Parameters
attribute (unicode or byte string) – the key for an attribute value
- Returns
the value corresponding to
attribute, as unicode- Return type
unicode
- Raises
KeyError – if no value found for
attributeUnicodeDecodeError – if value is not convertible
-
asint(attribute)¶ Get the given
attributeas an int.- Parameters
attribute (unicode or byte string) – the key for an attribute value
- Returns
the value corresponding to
attribute, as an int- Return type
- Raises
KeyError – if no value found for
attributeUnicodeDecodeError – if value is not convertible to unicode
ValueError – if unicode value can not be converted to an int
-
asbool(attribute)¶ Get the given
attributefrom this device as a bool.- Parameters
attribute (unicode or byte string) – the key for an attribute value
- Returns
the value corresponding to
attribute, as bool- Return type
- Raises
KeyError – if no value found for
attributeUnicodeDecodeError – if value is not convertible to unicode
ValueError – if unicode value can not be converted to a bool
A boolean attribute has either a value of
'1'or of'0', where'1'stands forTrue, and'0'forFalse. Any other value causes aValueErrorto be raised.
-
-
class
pyudev.Tags¶ A iterable over
Devicetags.Subclasses the
Containerand theIterableABC.-
__iter__()¶ Iterate over all tags.
Yield each tag as unicode string.
-
__contains__(tag)¶ Check for existence of
tag.tagis a tag as unicode string.Return
True, iftagis attached to the device,Falseotherwise.
-
Device exceptions¶
-
class
pyudev.DeviceNotFoundError¶ An exception indicating that no
Devicewas found.Changed in version 0.5: Rename from
NoSuchDeviceErrorto its current name.
-
class
pyudev.DeviceNotFoundAtPathError(sys_path)¶ A
DeviceNotFoundErrorindicating that noDevicewas found at a given path.-
property
sys_path¶ The path that caused this error as string.
-
property
-
class
pyudev.DeviceNotFoundByNameError(subsystem, sys_name)¶ A
DeviceNotFoundErrorindicating that noDevicewas found with a given name.-
property
subsystem¶ The subsystem that caused this error as string.
-
property
sys_name¶ The sys name that caused this error as string.
-
property
-
class
pyudev.DeviceNotFoundByNumberError(typ, number)¶ A
DeviceNotFoundErrorindicating, that noDevicewas found for a given device number.-
property
device_number¶ The device number causing this error as integer.
-
property
device_type¶ The device type causing this error as string. Either
'char'or'block'.
-
property
-
class
pyudev.DeviceNotFoundInEnvironmentError¶ A
DeviceNotFoundErrorindicating, that noDevicecould be constructed from the process environment.
Monitor – device monitoring¶
-
class
pyudev.Monitor¶ A synchronous device event monitor.
A
Monitorobjects 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 (seefrom_netlink()):>>> from pyudev import Context, Monitor >>> context = Context() >>> monitor = Monitor.from_netlink(context)
Once the monitor is created, you can add a filter using
filter_by()orfilter_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
MonitorObserver.To integrate into various event processing frameworks, the monitor provides a
selectablefile description byfileno(). 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 throughctypes.Changed in version 0.16: Remove
from_socket()which is deprecated, and even removed in recent udev versions.-
classmethod
from_netlink(context, source='udev')¶ Create a monitor by connecting to the kernel daemon through netlink.
contextis theContextto use.sourceis 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
Monitorobject, which is connected to the given source. RaiseValueError, if an invalid source has been specified. RaiseEnvironmentError, if the creation of the monitor failed.
-
started¶ True, if this monitor was started,Falseotherwise. Readonly.See also
New in version 0.16.
-
fileno()¶ Return the file description associated with this monitor as integer.
This is really a real file descriptor ;), which can be watched and
select.select()ed.
-
filter_by(subsystem, device_type=None)¶ Filter incoming events.
subsystemis 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_typeis a byte or unicode string specifying the device type. Only devices with the given device type are propagated to the caller. Ifdevice_typeis 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.
Changed in version 0.15: This method can also be after
start()now.
-
filter_by_tag(tag)¶ Filter incoming events by the given
tag.tagis 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
filter_by()this filter is also executed inside the kernel, so that client processes are usually not woken up for devices without the giventag.Required udev version: 154
New in version 0.9.
Changed in version 0.15: This method can also be after
start()now.
-
remove_filter()¶ Remove any filters installed with
filter_by()orfilter_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 raisesValueError.Raise
EnvironmentErrorif removal of installed filters failed.New in version 0.15.
-
start()¶ Start this monitor.
The monitor will not receive events until this method is called. This method does nothing if called on an already started
Monitor.Note
Typically you don’t need to call this method. It is implicitly called by
poll()and__iter__().See also
Changed in version 0.16: This method does nothing if the
Monitorwas already started.
-
set_receive_buffer_size(size)¶ Set the receive buffer
size.sizeis 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
EnvironmentErrorwill be raised, witherrnoset toEPERM. 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
EnvironmentError, if the buffer size could not bet set.New in version 0.13.
-
poll(timeout=None)¶ Poll for a device event.
You can use this method together with
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
Noneif notimeoutis specified, this is effectively an endless loop. Withfunctools.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.
timeoutis a floating point number that specifies a time-out in seconds. If omitted orNone, this method blocks until a device event is available. If0, this method just polls and will never block.Note
This method implicitly calls
start().Return the received
Device, orNoneif a timeout occurred. RaiseEnvironmentErrorif event retrieval failed.See also
Device.actionThe action that created this event.
Device.sequence_numberThe sequence number of this event.
New in version 0.16.
Deprecated members
-
enable_receiving()¶ 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
__iter__(). You don’t need to call it explicitly, if you are iterating over the monitor.Deprecated since version 0.16: Will be removed in 1.0. Use
start()instead.
-
receive_device()¶ Receive a single device from the monitor.
Warning
You must call
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).deviceis theDeviceobject describing the device.actionis 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
EnvironmentError, if no device could be read.Deprecated since version 0.16: Will be removed in 1.0. Use
Monitor.poll()instead.
-
__iter__()¶ Wait for incoming events and receive them upon arrival.
This methods implicitly calls
start(), and starts polling thefileno()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)(seereceive_device()for a description).Deprecated since version 0.16: Will be removed in 1.0. Use an explicit loop over
poll()instead, or monitor asynchronously withMonitorObserver.
-
classmethod
MonitorObserver – asynchronous device monitoring¶
-
class
pyudev.MonitorObserver(monitor, event_handler=None, callback=None, *args, **kwargs)¶ An asynchronous observer for device events.
This class subclasses
Threadclass to asynchronously observe aMonitorin 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
stop()is called onobserver.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
daemontoFalsebefore invokingstart().See also
Device.actionThe action that created this event.
Device.sequence_numberThe sequence number of this event.
New in version 0.14.
Changed in version 0.15:
Monitor.start()is implicitly called when the thread is started.-
__init__(monitor, event_handler=None, callback=None, *args, **kwargs)¶ Create a new observer for the given
monitor.monitoris theMonitorto observe.callbackis the callable to invoke on events, with the signaturecallback(device)wheredeviceis theDevicethat caused the event.Warning
callbackis invoked in the observer thread, hence the observer is blocked while callback executes.argsandkwargsare passed unchanged to the constructor ofThread.Deprecated since version 0.16: The
event_handlerargument will be removed in 1.0. Use thecallbackargument instead.Changed in version 0.16: Add
callbackargument.
-
send_stop()¶ 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
stop().Note
The underlying
monitoris not stopped.
-
stop()¶ Synchronously stop the background thread.
Note
This method can safely be called from the observer thread. In this case it is equivalent to
send_stop().Send a stop signal to the backgroud (see
send_stop()), and waits for the background thread to exit (seejoin()) if the current thread is not the observer thread.After this method returns in a thread that is not the observer thread, the
callbackis guaranteed to not be invoked again anymore.Note
The underlying
monitoris not stopped.Changed in version 0.16: This method can be called from the observer thread.