4

我正在尝试在 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
4

1 回答 1

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()
于 2013-03-21T13:44:40.810 回答