Get drives and partitions list (Linux)

Jeff Epler jepler at unpythonic.net
Sun Jun 12 21:52:22 EDT 2005


Using /proc/partitions is probably preferable because any user can read
it, not just people who can be trusted with read access to drives, and
because the format of /proc/partitions is probably simpler and more
stable over time.

That said, what you do is
    import commands
    fdisk_output = commands.getoutput("fdisk -l %s" % partition)
followed by some specialized code to parse the output of 'fdisk -l'
The following code is not at all tested, but might do the trick.

# python parse_fdisk.py
/dev/hda4 blocks=1060290 bootable=False partition_id_string='Linux swap' partition_id=130 start=8451 end=8582
/dev/hda1 blocks=15634048 bootable=True partition_id_string='HPFS/NTFS' partition_id=7 start=1 end=1947
/dev/hda3 blocks=9213277 bootable=False partition_id_string='W95 FAT32 (LBA)' partition_id=12 start=8583 end=9729
/dev/hda2 blocks=52235347 bootable=False partition_id_string='Linux' partition_id=131 start=1948 end=8450

# This source code is placed in the public domain
def parse_fdisk(fdisk_output):
    result = {}
    for line in fdisk_output.split("\n"):
        if not line.startswith("/"): continue
        parts = line.split()

        inf = {}
        if parts[1] == "*":
            inf['bootable'] = True
            del parts[1]
        else:
            inf['bootable'] = False

        inf['start'] = int(parts[1])
        inf['end'] = int(parts[2])
        inf['blocks'] = int(parts[3].rstrip("+"))
        inf['partition_id'] = int(parts[4], 16)
        inf['partition_id_string'] = " ".join(parts[5:])

        result[parts[0]] = inf
    return result

def main():
    import commands
    fdisk_output = commands.getoutput("fdisk -l /dev/hda")
    for disk, info in parse_fdisk(fdisk_output).items():
        print disk, " ".join(["%s=%r" % i for i in info.items()])

if __name__ == '__main__': main()
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050612/9d269c64/attachment.sig>


More information about the Python-list mailing list