My final code is this.
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)
As long as you mount read-only or use journaling filesystems like ext4 or NTFS (not sure) you should not have any problem with data integrity when just pulling the plug. Unmounting not required in that case, the mount automatically disappears.
TODO: python complains about outdated GObject.MainLoop()