【发布时间】:2013-03-06 22:45:45
【问题描述】:
我正在尝试用 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()是卡在哪一行? -
@CameronSparr 它不会卡住,因为它不会失败并退出。当 waitforusb() 被调用时,它被卡住了,它做了它应该做的事情,并且 device_add_callback(device) 被正确调用,USB 块设备被列出,.join 和 .endswith 工作正常(所以我可以检查是否分区已注册...就是这样),但是我不知道下一步该怎么做才能摆脱 dbus 位。我已经尝试过各种 True;打破循环......无济于事。
-
我不确定我是否理解问题...正在执行打印语句吗? “爆发”是什么意思?
-
我认为你可能对它卡在
mainloop.run()中是正确的,但我的大脑今天变得糊状,我不知道如何让它等待 udev 返回那个块设备已被添加(或循环轮询),然后继续检查 mtab,检查文件位。 -
link 说我可以使用
mainloop.quit()杀死它,但我不知道该放在哪里。如果我把它放在mainloop.run()之后,它不会被执行;如果我把它放在def device_added_callback(device):里面的某个地方,那么我会抛出一个异常,因为 mainloop 在那个 def 中不存在!