我正在尝试使用Python制作一个系统来检查USB驱动器上是否存在文件,如果没有驱动器,则等待dbus系统注册新设备然后再次检查。
我检查了mtab位。我检查文件是否存在位。我的dbus位工作正常,但我现在正在努力解决的问题是当驱动器注册时让它突破dbus位,这样我就可以检查mtab然后检查文件。
我希望这是有道理的。
我会为糟糕的编码风格道歉 - 我只是进入它。
这是我到目前为止所做的:
#!/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
答案 0 :(得分:1)
知道了!
我非常怀疑这是最优雅的解决方案,但我会在稍后阶段攻击优雅。
我将mainloop设为全局,然后我可以从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()