【问题标题】:(auto-)mount (usb-)drives through udisk2 dbus api from python(自动)挂载(usb-)驱动器通过来自python的udisk2 dbus api
【发布时间】:2021-04-04 09:45:37
【问题描述】:

我有一个控制音频播放器的 python 守护程序。 现在我想让这个守护进程监控插入的 USB 磁盘并将它们的内容添加到 mpd 媒体库。

其中一部分是 udisk 客户端,它等待磁盘插入,然后立即挂载它们。

我想以只读方式挂载磁盘,所以如果我不先卸载或关闭就拔下磁盘,不会有任何数据损坏。

【问题讨论】:

标签: linux automount udisks


【解决方案1】:

我的最终代码是这样的。

def start_listening():
    import dbus
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()

    def cb_insert_disk(*args):
        device = args[0]
        info = args[1]
        if "org.freedesktop.UDisks2.Block" in info:
            if 'org.freedesktop.UDisks2.Partition' in info:
                drive = info['org.freedesktop.UDisks2.Block']['Drive']
                fs = info['org.freedesktop.UDisks2.Partition']['Type']
                print("Mounting", fs, device, "on", drive, "to ...")
                obj = bus.get_object('org.freedesktop.UDisks2', device)
                #mountpoint = obj.Mount(dict(fstype=fs, options="ro"), dbus_interface="org.freedesktop.UDisks2.Filesystem")
                mountpoint = obj.Mount(dict(options="ro"), dbus_interface="org.freedesktop.UDisks2.Filesystem")
                print("Mounted to ", mountpoint)

    bus.add_signal_receiver(cb_insert_disk, 'InterfacesAdded',   'org.freedesktop.DBus.ObjectManager')

    # start the listener loop
    from gi.repository import GObject
    loop = GObject.MainLoop()
    loop.run()

# start a seprate listener thread
thread=threading.Thread(target=start_listening)
thread.daemon=True # enable CTRL+C for aborting
thread.start()

# And our program will continue in this pointless loop
while True:
    time.sleep(1)

只要您以只读方式挂载或使用 ext4 或 NTFS 之类的日志文件系统(不确定),只要拔掉插头,数据完整性就不会有任何问题。在这种情况下不需要卸载,挂载会自动消失。

TODO:python 抱怨过时的GObject.MainLoop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多