问题打印python中的usb挂载点

时间:2010-12-07 04:44:01

标签: python usb subprocess dbus

我有一个用python编写的程序,它使用dbus来检测插入的USB驱动器,并在检测到它们时打印它们所安装的目录。这是代码:

 
import dbus
import gobject
import shutil
import os
import subprocess
import time

class DeviceAddedListener:
    def __init__(self):
    self.bus = dbus.SystemBus()
        self.hal_manager_obj = self.bus.get_object(
                                              "org.freedesktop.Hal", 
                                              "/org/freedesktop/Hal/Manager")
        self.hal_manager = dbus.Interface(self.hal_manager_obj,
                                          "org.freedesktop.Hal.Manager")
    self.hal_manager.connect_to_signal("DeviceAdded", self._filter)

    def _filter(self, udi):
        device_obj = self.bus.get_object ("org.freedesktop.Hal", udi)
        device = dbus.Interface(device_obj, "org.freedesktop.Hal.Device")

        if device.QueryCapability("volume"):
            return self.do_something(device)

    def do_something(self, volume):
        device_file = volume.GetProperty("block.device")
        label = volume.GetProperty("volume.label")
        fstype = volume.GetProperty("volume.fstype")
        mounted = volume.GetProperty("volume.is_mounted")
        mount_point = volume.GetProperty("volume.mount_point")
        try:
            size = volume.GetProperty("volume.size")
        except:
            size = 0
    p1 = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(["grep", device_file], stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(["awk", "{ print $6 }"], stdin=p2.stdout, stdout=subprocess.PIPE)
    path = p3.communicate()[0]
    print path



if __name__ == '__main__':
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    DeviceAddedListener()
    loop.run()

问题是当我打印路径变量(usb的挂载点)时,它会打印一个空字符串。但是,当我在python交互式解释器中执行这些相同的命令(Popen()等)时,它会很好地打印路径(/ media / 03CB-604C)。为什么会这样?对我的代码的任何编辑/建议将非常感激。提前谢谢!

1 个答案:

答案 0 :(得分:1)

在您的原始问题中,您可能会被竞争条件殴打。

插入设备并在安装过程完成之前执行代码。

尝试将Popen调用放入while循环(见下文)。

path = ""
count = 0
while count < 10 and path == "":
    p1 = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(["grep", device_file], stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(["awk", "{ print $6 }"], stdin=p2.stdout, stdout=subprocess.PIPE)
    path = p3.communicate()[0]
    count += 1
    if path == "":
        time.sleep(1)
print path

这是一个需要资源的解决方案,但它应该做你想要的。