2010-12-07 10 views
2

我有一個用python編寫的程序,它使用dbus來檢測插入的usb驅動器,並在檢測到它們時打印它們安裝的目錄。下面是代碼:在python中打印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

「p1 ... p2 ...行顯示錯誤嗎?它們是否是」do_something「的一部分? – mjhm 2010-12-07 06:28:21

回答

1

在你原來的問題中,你很可能被競爭條件毆打。

插入設備並在安裝過程完成之前執行您的代碼。

嘗試在一個while循環中放置Popen調用(見下文)。

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 

這是一個資源飢渴的解決方案,但它應該做你想做的。