Skip to main content
 首页 » 编程设计

python之在python中打印usb的挂载点时出现问题

2025年05月04日6mfrbuaa

我有一个用 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)。为什么会发生这种情况?对我的代码的任何编辑/建议将不胜感激。提前致谢!

请您参考如下方法:

在您最初的问题中,您似乎被比赛条件打败了。

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

尝试将 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 

这是一个有点耗费资源的解决方案,但它应该可以满足您的需求。