Is there any daemon/tool which will trigger some signal/event when USB keyboard is plugged and unplugged from pc? I need to know in my 开发者_运维百科program when USB keyboard is plugged and unplugged. Any ideas on how to do this?
udev (Linux device manager) is the one that polls hardware. When it detects some changes about devices, it executes the rule associated.
You should add a rule to udev, in order to inform your program about insertion of removal of USB keyboard. You can find documentation about udev rules here, or Look at files in /etc/udev/rules.d/
or /lib/udev/rules.d/
to find many examples.
udevadm monitor
(the udev administration binary) or udev_monitor
(in libudev).
Alternately, if you're running in X11 with input hotplugging, you can listen for the XI extension event DevicePresenceNotify
.
If HAL daemon is running (which is true for most modern linux desktops), you can listen to its DBus Signals. Here is an example how to detect if a USB mouse is plugged in (I don't have a USB keyboard at hand):
import gobject
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
# enumerate all present mice:
manager = dbus.Interface(bus.get_object("org.freedesktop.Hal",
"/org/freedesktop/Hal/Manager"),
"org.freedesktop.Hal.Manager")
mice = set(manager.FindDeviceByCapability('input.mouse'))
def device_added(sender):
dev = dbus.Interface(bus.get_object("org.freedesktop.Hal", sender),
"org.freedesktop.Hal.Device")
try:
caps = dev.GetProperty('info.capabilities')
if 'input.mouse' in caps:
print "mouse plugged in"
mice.add(sender)
except dbus.DBusException:
pass
def device_removed(sender):
if sender in mice:
print "mouse unplugged"
mice.remove(sender)
bus.add_signal_receiver(device_added, signal_name="DeviceAdded")
bus.add_signal_receiver(device_removed, signal_name="DeviceRemoved")
loop = gobject.MainLoop()
loop.run()
精彩评论