我正在尝试用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
mainloop.run()
是它卡在那里的那一行代码吗? - Cameron Sparrmainloop.run()
上的想法可能是正确的,但今天我的大脑已经变成了浆糊,我无法想出如何让它等待udev返回块设备已添加(或在循环中轮询),然后继续检查mtab、检查文件位。 - Grantmainloop.quit()
来终止它,但我不确定在哪里放置它。如果我将其放置在mainloop.run()
之后,它将不会被执行;如果我将其放置在def device_added_callback(device):
内的某个位置,则会抛出异常,因为该def内不存在mainloop! - Grant