Check USB drive on Linux in Python?

I am trying to create a system in Python that checks if a file exists on a USB drive, and if there is no drive, it expects the dbus system to register a new device and then check again.

I have the mtab bit checked. I have a check if the file exists a bit. My dbus bit is working, but I'm currently struggling with it, so make it break out of the dbus bit when the disk is registered, so I can check mtab and then check the file.

I hope this made sense.

I apologize for the bad coding style - I just delve into it.

This is what I have so far:

#!/usr/bin/env python import string, time, os, dbus, gobject, sys from dbus.mainloop.glib import DBusGMainLoop def device_added_callback(device): print ("Block device added. Check if it is partitioned") usbdev = "".join(device.split("/")[5:6]) if usbdev.endswith("1") == 1: print ("Block device is partitioned. Waiting for it to be mounted.") # This is where I need to break out of the USB bit so I can check mtab and then check the file exits. def waitforusb(): DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() proxy = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks") iface = dbus.Interface(proxy, "org.freedesktop.UDisks") devices = iface.get_dbus_method('EnumerateDevices')() usbdev = iface.connect_to_signal('DeviceAdded', device_added_callback) mainloop = gobject.MainLoop() mainloop.run() return usbdev def checkusbispresent(): f = open("/etc/mtab") lines = f.readlines() f.close() for line in lines: mtpt = "".join(line.split()[1:2]) isthere = mtpt.find("media") if isthere == 1: return mtpt def checkserialfile(mtpt): _serialfile=mtpt+"/serial.lic" if ( not os.path.isfile(_serialfile)): print("Error: serial file not found, please download it now") else: print("Serial file found, attempting validation... ") usbdrive = checkusbispresent() if ( usbdrive is not None ): checkserialfile(usbdrive) else: print ("USB drive is not present. Please add it now.") added = waitforusb() print added 
+4
source share
1 answer

Got it!

I doubt very much that this is the most elegant solution, but I will attack elegance at a later stage.

I made mainloop global, and then I was able to access it from inside device_added_callback:

 def waitforusb(): DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() proxy = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks") iface = dbus.Interface(proxy, "org.freedesktop.UDisks") devices = iface.get_dbus_method('EnumerateDevices')() iface.connect_to_signal('DeviceAdded', device_added_callback) global mainloop mainloop = gobject.MainLoop() mainloop.run() def device_added_callback(device): usbdev = "".join(device.split("/")[5:6]) if usbdev.endswith("1") == 1: mainloop.quit() 
+1
source

All Articles