pyudev: libudev Binding
pyudev is an LGPL-licensed, pure Python binding for libudev, the device and hardware management library for Linux. It provides functionality to enumerate devices, query their properties and attributes, and monitor device events, including asynchronous monitoring with various GUI toolkit integrations. The current version is 0.24.4 and it supports CPython 3.9 and newer. It is actively maintained with development on GitHub.
Warnings
- gotcha Using a `Device` object in a boolean context (e.g., `if device:`) can yield `False` if the device has no udev properties, even if the device itself is valid. This is due to `Device` inheriting from `Mapping`. Explicitly check for `None` or specific properties instead.
- deprecated Accessing udev properties directly via `Device` object indexing (e.g., `device['PROPERTY']`) is deprecated since version 0.21.0. The `Device` class no longer behaves like a mapping for properties.
- gotcha Do not use object identity (`is` operator) to compare `Device` objects (e.g., `device1 is device2`). `pyudev` may create multiple `Device` objects that refer to the same underlying udev device. Compare them by value using `==` or `!=` instead.
- deprecated Methods like `Device.from_sys_path()`, `Device.from_name()`, and `Device.from_device_file()` were deprecated in version 0.18.
Install
-
pip install pyudev
Imports
- Context
from pyudev import Context
- Device
from pyudev import Device
- Monitor
from pyudev import Monitor
- MonitorObserver
from pyudev import MonitorObserver
- Devices
from pyudev import Devices
Quickstart
import pyudev
# Create a udev context
context = pyudev.Context()
# Enumerate all block devices that are partitions and print their labels
print('Listing partitions:')
for device in context.list_devices(subsystem='block', DEVTYPE='partition'):
# Use device.get() for properties, providing a default for safety
label = device.get('ID_FS_LABEL', 'unlabeled partition')
print(f" {device.device_node}: {label}")
# Monitor for new USB devices (example)
print('\nMonitoring for new USB devices (Ctrl+C to stop):')
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
monitor.start() # Start the monitor to receive events
for action, device in monitor:
if action == 'add':
print(f" Added USB device: {device.sys_name} ({device.get('ID_VENDOR_FROM_DATABASE', 'Unknown Vendor')})")