pyudev: libudev Binding

0.24.4 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart initializes a udev context, then demonstrates enumerating all block device partitions and printing their file system labels. It also shows how to set up a monitor to listen for new USB device 'add' events in real-time.

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')})")

view raw JSON →