python - 如何在 Python 中监听 Linux 中的 'usb device inser

我想在 Linux 中为 Amarok 编写一个 Python 脚本,以自动将 stackoverflow 播客复制到我的播放器。当我插入播放器时,它会安装驱动器,复制任何待处理的播客,然后弹出播放器。如何收听“插入”事件?我已经浏览了一遍,但找不到一个很好的例子。

最佳答案

更新:正如评论中所说,最近的发行版不支持Hal,现在的标准是udev,这是一个利用glib循环和udev的小例子>,出于历史原因,我保留了 Hal 版本。

这基本上是 example in the pyudev documentation ,适用于旧版本和 glib 循环,请注意过滤器应根据您的特定需求进行定制:

import glib

from pyudev import Context, Monitor

try:
    from pyudev.glib import MonitorObserver

    def device_event(observer, device):
        print 'event {0} on device {1}'.format(device.action, device)
except:
    from pyudev.glib import GUDevMonitorObserver as MonitorObserver

    def device_event(observer, action, device):
        print 'event {0} on device {1}'.format(action, device)

context = Context()
monitor = Monitor.from_netlink(context)

monitor.filter_by(subsystem='usb')
observer = MonitorObserver(monitor)

observer.connect('device-event', device_event)
monitor.start()

glib.MainLoop().run()

带有 Hal 和 d-bus 的旧版本:

您可以使用 D-Bus 绑定(bind)并监听 DeviceAddedDeviceRemoved 信号。 您必须检查已添加设备的功能才能仅选择存储设备。

这里是一个小例子,你可以去掉评论试试看。

import dbus
import gobject

class DeviceAddedListener:
    def __init__(self):

您需要使用系统总线连接到 Hal Manager。

        self.bus = dbus.SystemBus()
        self.hal_manager_obj = self.bus.get_object(
                                              "org.freedesktop.Hal", 
                                              "/org/freedesktop/Hal/Manager")
        self.hal_manager = dbus.Interface(self.hal_manager_obj,
                                          "org.freedesktop.Hal.Manager")

您需要将监听器连接到您感兴趣的信号,在本例中为 DeviceAdded

        self.hal_manager.connect_to_signal("DeviceAdded", self._filter)

我正在使用基于功能的过滤器。它将接受任何 volume 并使用 if 调用 do_something,您可以阅读 Hal 文档以找到更适合您需求的查询,或有关 Hal 属性的更多信息设备。

    def _filter(self, udi):
        device_obj = self.bus.get_object ("org.freedesktop.Hal", udi)
        device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device")

        if device.QueryCapability("volume"):
            return self.do_something(device)

显示有关卷的一些信息的示例函数:

     def do_something(self, volume):
        device_file = volume.GetProperty("block.device")
        label = volume.GetProperty("volume.label")
        fstype = volume.GetProperty("volume.fstype")
        mounted = volume.GetProperty("volume.is_mounted")
        mount_point = volume.GetProperty("volume.mount_point")
        try:
            size = volume.GetProperty("volume.size")
        except:
            size = 0

        print "New storage device detectec:"
        print "  device_file: %s" % device_file
        print "  label: %s" % label
        print "  fstype: %s" % fstype
        if mounted:
            print "  mount_point: %s" % mount_point
        else:
            print "  not mounted"
        print "  size: %s (%.2fGB)" % (size, float(size) / 1024**3)

if __name__ == '__main__':
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    DeviceAddedListener()
    loop.run()

关于python - 如何在 Python 中监听 Linux 中的 'usb device inserted' 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/469243/

相关文章:

linux - 永久反转补丁文件

linux - 是否有一个 linux 命令来确定与给定进程 ID 关联的窗口 ID?

linux - Bash 将 awk 的输出捕获到数组中

php - 脚本 "/home/...../public_html/index.php"的 UID

c++ - 我在哪里放置第三方库来设置 C++ Linux 开发环境?

c - glibconfig.h 没有这样的文件或目录

linux - 在像 "f () {}"这样的 bash shell 脚本函数定义中使用的括号是什么

linux - 如果关键字触发然后执行命令,Shell 脚本来监视日志文件?

linux - 如何从 X session 之外(例如从控制台或 SSH)运行 X 程序

php - 根据外部请求在 Netbeans 中启动 XDebug