Get drives and partitions list (Linux)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cantabile

    Get drives and partitions list (Linux)

    Hi, I'd like to get drives and partitions (and their size too) with
    python under Linux. So far, I thought of reading /proc/partitions but
    maybe i could use fdsik also ?
    How would I do that in python ?

    Thanks for your help (newbie here :) )
  • Jeff Epler

    #2
    Re: Get drives and partitions list (Linux)

    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.getout put("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_st ring='Linux swap' partition_id=13 0 start=8451 end=8582
    /dev/hda1 blocks=15634048 bootable=True partition_id_st ring='HPFS/NTFS' partition_id=7 start=1 end=1947
    /dev/hda3 blocks=9213277 bootable=False partition_id_st ring='W95 FAT32 (LBA)' partition_id=12 start=8583 end=9729
    /dev/hda2 blocks=52235347 bootable=False partition_id_st ring='Linux' partition_id=13 1 start=1948 end=8450

    # This source code is placed in the public domain
    def parse_fdisk(fdi sk_output):
    result = {}
    for line in fdisk_output.sp lit("\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_s tring'] = " ".join(part s[5:])

    result[parts[0]] = inf
    return result

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

    if __name__ == '__main__': main()

    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.2.6 (GNU/Linux)

    iD8DBQFCrObVJd0 1MZaTXX0RAt6FAJ 9dDvaJ1L5fxTbvt WCSv7If/eHNaQCdFBcI
    fHHR0kcAYQA1Sw5 t2BDMMqQ=
    =LHbf
    -----END PGP SIGNATURE-----

    Comment

    • Peter Hansen

      #3
      Re: Get drives and partitions list (Linux)

      cantabile wrote:[color=blue]
      > Hi, I'd like to get drives and partitions (and their size too) with
      > python under Linux. So far, I thought of reading /proc/partitions but
      > maybe i could use fdsik also ?
      > How would I do that in python ?[/color]

      Somebody else posted a very similar question quite recently. A Google
      Groups search would probably lead you to the answers pretty quickly.
      (Try "partition proc sfdisk" or something like that.)

      My previous answer was to call sfdisk, using os.popen(). Others
      suggested reading /proc/partitions. I doubt fdisk (if that's what you
      meant) is a good idea.

      There is no pure Python solution, so far as I know, probably because
      there may not be any standardized way of finding this information.

      -Peter

      Comment

      • cantabile

        #4
        Re: Get drives and partitions list (Linux)

        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:[color=blue]
        > 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.getout put("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_st ring='Linux swap' partition_id=13 0 start=8451 end=8582
        > /dev/hda1 blocks=15634048 bootable=True partition_id_st ring='HPFS/NTFS' partition_id=7 start=1 end=1947
        > /dev/hda3 blocks=9213277 bootable=False partition_id_st ring='W95 FAT32 (LBA)' partition_id=12 start=8583 end=9729
        > /dev/hda2 blocks=52235347 bootable=False partition_id_st ring='Linux' partition_id=13 1 start=1948 end=8450
        >
        > # This source code is placed in the public domain
        > def parse_fdisk(fdi sk_output):
        > result = {}
        > for line in fdisk_output.sp lit("\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_s tring'] = " ".join(part s[5:])
        >
        > result[parts[0]] = inf
        > return result
        >
        > def main():
        > import commands
        > fdisk_output = commands.getout put("fdisk -l /dev/hda")
        > for disk, info in parse_fdisk(fdi sk_output).item s():
        > print disk, " ".join(["%s=%r" % i for i in info.items()])
        >
        > if __name__ == '__main__': main()[/color]

        Comment

        • cantabile

          #5
          Re: Get drives and partitions list (Linux)

          Hi, Peter
          Thanks for the reply. I'll check popen().
          But you said I should not rely on fdisk... Why ? And should I prefer
          sfdisk ? Why ?


          Peter Hansen wrote:[color=blue]
          > cantabile wrote:
          >[color=green]
          >> Hi, I'd like to get drives and partitions (and their size too) with
          >> python under Linux. So far, I thought of reading /proc/partitions but
          >> maybe i could use fdsik also ?
          >> How would I do that in python ?[/color]
          >
          >
          > Somebody else posted a very similar question quite recently. A Google
          > Groups search would probably lead you to the answers pretty quickly.
          > (Try "partition proc sfdisk" or something like that.)
          >
          > My previous answer was to call sfdisk, using os.popen(). Others
          > suggested reading /proc/partitions. I doubt fdisk (if that's what you
          > meant) is a good idea.
          >
          > There is no pure Python solution, so far as I know, probably because
          > there may not be any standardized way of finding this information.
          >
          > -Peter[/color]

          Comment

          • Peter Hansen

            #6
            Re: Get drives and partitions list (Linux)

            cantabile wrote:[color=blue]
            > Hi, Peter
            > Thanks for the reply. I'll check popen().
            > But you said I should not rely on fdisk... Why ? And should I prefer
            > sfdisk ? Why ?[/color]

            I was under the impression that fdisk was older and more primitive, but
            a quick check shows I'm probably not only wrong, but had it backwards!
            (The man page for fdisk says "try parted, then fdisk, then sfdisk"
            basically...)

            Also, as you saw in Jeff's reply, there's a commands.getout put()
            function that does basically what popen() would do, so just use whatever
            seems simplest.

            -Peter

            Comment

            • cantabile

              #7
              Re: Get drives and partitions list (Linux)

              Thanks for the answer and help.
              Cheers :)

              Peter Hansen wrote:[color=blue]
              > cantabile wrote:
              >[color=green]
              >> Hi, Peter
              >> Thanks for the reply. I'll check popen().
              >> But you said I should not rely on fdisk... Why ? And should I prefer
              >> sfdisk ? Why ?[/color]
              >
              >
              > I was under the impression that fdisk was older and more primitive, but
              > a quick check shows I'm probably not only wrong, but had it backwards!
              > (The man page for fdisk says "try parted, then fdisk, then sfdisk"
              > basically...)
              >
              > Also, as you saw in Jeff's reply, there's a commands.getout put()
              > function that does basically what popen() would do, so just use whatever
              > seems simplest.
              >
              > -Peter[/color]

              Comment

              Working...