pyudev.monitor module¶
Monitor implementation.
- class pyudev.monitor.Monitor(context, monitor_p)¶
- Bases: - object- 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 (see- 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 - filter_by()or- 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 - MonitorObserver.- To integrate into various event processing frameworks, the monitor provides a - selectablefile description by- 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- ctypes.- Changed in version 0.16: Remove - from_socket()which is deprecated, and even removed in recent udev versions.- 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.
 - 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. If- device_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 given- tag.- Required udev version: 154 - Added in version 0.9. - Changed in version 0.15: This method can also be after - start()now.
 - classmethod from_netlink(context, source='udev')¶
- Create a monitor by connecting to the kernel daemon through netlink. - contextis the- Contextto 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. Raise- ValueError, if an invalid source has been specified. Raise- EnvironmentError, if the creation of the monitor failed.
 - 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 no- timeoutis specified, this is effectively an endless loop. With- 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. - timeoutis 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 - start().- Return the received - Device, or- Noneif a timeout occurred. Raise- EnvironmentErrorif event retrieval failed.- See also - Device.action
- The action that created this event. 
- Device.sequence_number
- The sequence number of this event. 
 - Added in version 0.16. 
 - 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 the- Deviceobject 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.
 - remove_filter()¶
- Remove any filters installed with - filter_by()or- 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- ValueError.- Raise - EnvironmentErrorif removal of installed filters failed.- Added in version 0.15. 
 - 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, with- errnoset to- 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 - EnvironmentError, if the buffer size could not bet set.- Added in version 0.13. 
 - 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.
 
- class pyudev.monitor.MonitorObserver(monitor, event_handler=None, callback=None, *args, **kwargs)¶
- Bases: - Thread- An asynchronous observer for device events. - This class subclasses - Threadclass to asynchronously observe a- Monitorin 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 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 - daemonto- Falsebefore invoking- start().- See also - Device.action
- The action that created this event. 
- Device.sequence_number
- The sequence number of this event. 
 - Added in version 0.14. - Changed in version 0.15: - Monitor.start()is implicitly called when the thread is started.- run()¶
- Method representing the thread’s activity. - You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. 
 - 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.
 - start()¶
- Start the observer thread. 
 - 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 (see- join()) 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.