Get drives and partitions list (Linux)

cantabile cantabile.03 at wanadoo.fr
Mon Jun 13 18:14:47 EDT 2005


Hi, Jeff

Great help : this works like a charm. I think I can customize it to read
from sfdisk. Do you agree with Peter Hansen (post below) about fdisk ?

Jeff Epler wrote:
> 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()



More information about the Python-list mailing list