2

recently I just started to use python3 and realised that there alot of changes made from python2.6. I want to know is there anyway to format the view of the hard disks available in a linux system by using fdisk? in python2.6, it worked something like this;

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():
    fdisk_output = commands.getoutput("fdisk -l")
    for disk, info in parse_fdisk(fdisk_output).items():
        print disk, " ".join(["%s=%r" % i for i in info.items()])
1
  • An actual description of your problem would have been useful. Commented Jan 15, 2012 at 13:36

2 Answers 2

6

Take a look at the psutil package.

psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory) in a portable way by using Python, implementing many functionalities offered by command line tools such as: ps, top, df, kill, free, lsof, netstat, ifconfig, nice, ionice, iostat, iotop, uptime, tty.

From their README:

It currently supports Linux, Windows, OSX and FreeBSD both 32-bit and 64-bit with Python versions from 2.4 to 3.3 by using a single code base.

Disk example:

>>> psutil.disk_partitions()
[partition(device='/dev/sda1', mountpoint='/', fstype='ext4'),
 partition(device='/dev/sda2', mountpoint='/home', fstype='ext4')]
>>>
>>> psutil.disk_usage('/')
usage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
>>>
>>> psutil.disk_io_counters()
iostat(read_count=719566, write_count=1082197, read_bytes=18626220032, 
       write_bytes=24081764352, read_time=5023392, write_time=63199568)

Partition details (e.g. bootable flag) aren't supported (yet), as far as I can tell.

Sign up to request clarification or add additional context in comments.

1 Comment

this is a very nice module to have. however, is there anyway i can grab out the partition details? I need to see the partition id of the hard disk aside from the hard disk name.
3

The commands module has been removed from Python3. You can use the subprocess module instead:

import subprocess
import shlex
import sys

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():
    proc = subprocess.Popen(shlex.split("fdisk -l"),
                            stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    fdisk_output, fdisk_error = proc.communicate()
    fdisk_output = fdisk_output.decode(sys.stdout.encoding)
    for disk, info in parse_fdisk(fdisk_output).items():
        print(disk, " ".join(["%s=%r" % i for i in info.items()]))

main()

No change was made to the parse_fdisk function. The only thing that needed changing was the call to commands.getoutput in main().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.