pah8J
pah8J

Reputation: 867

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

In Unix and Unix-like OS, the storage driver is mounted in a certain path. Is there any function in Python (3.x is better), that is able to get the name of device and partition number of a directory (for example / --> /dev/sda1 and /home --> /dev/sda2)?

Upvotes: 1

Views: 1295

Answers (1)

Abhi
Abhi

Reputation: 552

I am not sure about the source of the below code, but it did solve a similar problem I faced sometime back. The below code uses psutil to get information about all the mountpoints and devices. To install run 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 

You can tweak the code as per your requirements.

Upvotes: 2

Related Questions