如何使用python获取某路径的设备文件和分区号?

How to use python to get the device file and partition number of a certain path?

在 Unix 和类 Unix OS 中,存储驱动程序安装在特定路径中。 Python中有没有函数(3.x更好),可以获取设备名称和目录分区号(例如/ --> /dev/sda1/home --> /dev/sda2) ?

我不确定下面代码的来源,但它确实解决了我以前遇到的类似问题。 下面的代码使用 psutil 来获取有关所有挂载点和设备的信息。 安装 运行 pip install psutil

def disksinfo():
        values = []
        disk_partitions = psutil.disk_partitions(all=False)
        for partition in disk_partitions:
            usage = psutil.disk_usage(partition.mountpoint)
            device = {'device': partition.device,
                      'mountpoint': partition.mountpoint,
                      'fstype': partition.fstype,
                      'opts': partition.opts,
                      'total': usage.total,
                      'used': usage.used,
                      'free': usage.free,
                      'percent': usage.percent
                      }
            values.append(device)
        values = sorted(values, key=lambda device: device['device'])
        return values 

您可以根据需要调整代码。