Device – accessing device information

class pyudev.Device

A single device with attached attributes and properties.

This class subclasses the Mapping ABC, 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.

Device objects compare equal and unequal to other devices and to strings (based on device_path). However, there is no ordering on Device objects, and the corresponding operators >, <, <= and >= raise TypeError.

Warning

Do never use object identity (is operator) to compare Device objects. pyudev may create multiple Device objects for the same device. Instead simply compare devices by value using == or !=.

Device objects 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 through ctypes.

Construction of device objects

classmethod from_path(context, path)

Create a device from a device path. The path may or may not start with the sysfs mount point:

>>> context = pyudev.Context()
>>> Device.from_path(context, '/devices/platform')
Device(u'/sys/devices/platform')
>>> Device.from_path(context, '/sys/devices/platform')
Device(u'/sys/devices/platform')

context is the Context in which to search the device. path is a device path as unicode or byte string.

Return a Device object for the device. Raise DeviceNotFoundAtPathError, if no device was found for path.

New in version 0.4.

classmethod from_sys_path(context, sys_path)

Create a new device from a given sys_path:

>>> context = pyudev.Context()
>>> Device.from_path(context, '/sys/devices/platform')
Device(u'/sys/devices/platform')

context is the Context in which to search the device. sys_path is a unicode or byte string containing the path of the device inside sysfs with the mount point included.

Return a Device object for the device. Raise DeviceNotFoundAtPathError, if no device was found for sys_path.

Changed in version 0.4: Raise NoSuchDeviceError instead of returning None, if no device was found for sys_path

Changed in version 0.5: Raise DeviceNotFoundAtPathError instead of NoSuchDeviceError

classmethod from_name(context, subsystem, sys_name)

Create a new device from a given subsystem and a given sys_name:

>>> context = pyudev.Context()
>>> sda = pyudev.Device.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 == pyudev.Device.from_path(context, '/block/sda')

context is the Context in which to search the device. subsystem and sys_name are byte or unicode strings, which denote the subsystem and the name of the device to create.

Return a Device object for the device. Raise DeviceNotFoundByNameError, if no device was found with the given name.

New in version 0.5.

classmethod from_device_number(context, type, number)

Create a new device from a device number with the given device type:

>>> import os
>>> ctx = Context()
>>> major, minor = 8, 0
>>> device = Device.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.

Note

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.

context is the Context, in which to search the device. type is either 'char' or 'block', according to whether the device is a character or block device. number is the device number as integer.

Return a Device object for the device with the given device number. Raise DeviceNotFoundByNumberError, if no device was found with the given device type and number. Raise ValueError, if type is any other string than 'char' or 'block'.

New in version 0.11.

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.

context is the library Context.

Return a Device object constructed from the environment. Raise DeviceNotFoundInEnvironmentError, if no device could be created from the environment.

Required udev version: 152

New in version 0.6.

General attributes

context

The Context to which this device is bound.

New in version 0.5.

sys_path

Absolute path of this device in sysfs including the sysfs mount point as unicode string.

sys_name

Device file name inside sysfs as unicode string.

sys_number

The trailing number of the sys_name as unicode string, or None, 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:

>>> device = pyudev.Device.from_path(ctx, '/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 the sysfs mount point. However, the path is absolute and starts with a slash '/'.

tags

A Tags object representing the tags attached to this device.

The Tags object supports a test for a single tag as well as iteration over all tags:

>>> 'systemd' in device.tags
True
>>> list(device.tags)
[u'systemd', u'seat']

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 Tags object now.

Device driver and subsystem

subsystem

Name of the subsystem this device is part of as unicode string.

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.

>>> 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 (see Context.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_links to get a list of symbolic links to this device node.

device_number

The device number of the associated device as integer, or 0, if no device number is associated.

Use os.major() and os.minor() to decompose the device number into its major and minor number:

>>> context = Context()
>>> sda = Device.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 the st_rdev field of the stat result of the device_node:

>>> os.stat(sda.device_node).st_rdev
2048

New in version 0.11.

An iterator, which yields the absolute paths (including the device directory, see Context.device_path) of all symbolic links pointing to the device_node of 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.

Device initialization time

is_initialized

True, if the device is initialized, False otherwise.

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.

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

is_initialized

Required udev version: 165

New in version 0.8.

Device hierarchy

parent

The parent Device or None, if there is no parent device.

children

Yield all direct children of 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 Device object for each direct child of this device.

Required udev version: 172

Changed in version 0.13: Requires udev version 172 now.

traverse()

Traverse all parent devices of this device from bottom to top.

Return an iterable yielding all parent devices as Device objects, not including the current device. The last yielded Device is the top of the device hierarchy.

find_parent(subsystem, device_type=None)

Find the parent device with the given subsystem and device_type.

subsystem is a byte or unicode string containing the name of the subsystem, in which to search for the parent. device_type is a byte or unicode string holding the expected device type of the parent. It can be None (the default), which means, that no specific device type is expected.

Return a parent Device within the given subsystem and – if device_type is not None – with the given device_type, or None, if this device has no parent device matching these constraints.

New in version 0.9.

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.

__len__()

Return the amount of properties defined for this device as integer.

__getitem__(property)

Get the given property from this device.

property is 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.

asint(property)

Get the given property from this device as integer.

property is 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 a ValueError, if the property value cannot be converted to an integer.

asbool(property)

Get the given property from this device as boolean.

A boolean property has either a value of '1' or of '0', where '1' stands for True, and '0' for False. Any other value causes a ValueError to be raised.

property is a unicode or byte string containing the name of the property.

Return True, if the property value is '1' and False, if the property value is '0'. Any other value raises a ValueError. Raise a KeyError, if the given property is not defined for this device.

Sysfs attributes

attributes

The system attributes of this device as read-only Attributes mapping.

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.

class pyudev.Attributes

A mapping which holds udev attributes for Device objects.

This class subclasses the Mapping ABC, providing a read-only dictionary mapping attribute names to the corresponding values. Therefore all well-known dicitionary methods and operators (e.g. .keys(), .items(), in) are available to access device attributes.

New in version 0.5.

device

The Device to which these attributes belong.

__iter__()

Iterate over all attributes defined.

Yield each attribute name as unicode string.

__len__()

Return the amount of attributes defined.

__getitem__(attribute)

Get the given system attribute for the device.

attribute is a unicode or byte string containing the name of the system attribute.

Return the attribute value as byte string, or raise a KeyError, if the given attribute is not defined for this device.

asstring(attribute)

Get the given atribute for the device as unicode string.

Depending on the content of the attribute, this may or may not work. Be prepared to catch UnicodeDecodeError.

attribute is a unicode or byte string containing the name of the attribute.

Return the attribute value as byte string. Raise a KeyError, if the given attribute is not defined for this device, or UnicodeDecodeError, if the content of the attribute cannot be decoded into a unicode string.

asint(attribute)

Get the given attribute as integer.

attribute is a unicode or byte string containing the name of the attribute.

Return the attribute value as integer. Raise a KeyError, if the given attribute is not defined for this device, or a ValueError, if the attribute value cannot be converted to an integer.

asbool(attribute)

Get the given attribute from this device as boolean.

A boolean attribute has either a value of '1' or of '0', where '1' stands for True, and '0' for False. Any other value causes a ValueError to be raised.

attribute is a unicode or byte string containing the name of the attribute.

Return True, if the attribute value is '1' and False, if the attribute value is '0'. Any other value raises a ValueError. Raise a KeyError, if the given attribute is not defined for this device.

class pyudev.Tags

A iterable over Device tags.

Subclasses the Container and the Iterable ABC.

__iter__()

Iterate over all tags.

Yield each tag as unicode string.

__contains__(tag)

Check for existence of tag.

tag is a tag as unicode string.

Return True, if tag is attached to the device, False otherwise.

Exceptions

class pyudev.DeviceNotFoundError

An error indicating that no Device was found.

Changed in version 0.5: Renamed from NoSuchDeviceError to its current name.

class pyudev.DeviceNotFoundAtPathError(sys_path)

A DeviceNotFoundError indicating that no Device was found at a given path.

sys_path

The path that caused this error as string.

class pyudev.DeviceNotFoundByNameError(subsystem, sys_name)

A DeviceNotFoundError indicating that no Device was found with a given name.

subsystem

The subsystem that caused this error as string.

sys_name

The sys name that caused this error as string.

class pyudev.DeviceNotFoundByNumberError(type, number)

A DeviceNotFoundError indicating, that no Device was found for a given device number.

device_number

The device number causing this error as integer.

device_type

The device type causing this error as string. Either 'char' or 'block'.

class pyudev.DeviceNotFoundInEnvironmentError

A DeviceNotFoundError indicating, that no Device could be constructed from the process environment.

Project Versions

Table Of Contents

Previous topic

Context – the central object

Next topic

Monitor – monitor devices

This Page