Problem 6.7
Disk Usage
Get the disk usage of the computer using the df command.
The unix command df
prints the disk usage of every mounted filesystem on the computer.
$ df
Filesystem 1K-blocks Used Available Use% Mounted on
overlay 81106868 7855408 73235076 10% /
tmpfs 65536 0 65536 0% /dev
shm 65536 0 65536 0% /dev/shm
/dev/vda1 81106868 7855408 73235076 10% /home
tmpfs 2009932 0 2009932 0% /proc/acpi
tmpfs 2009932 0 2009932 0% /proc/scsi
tmpfs 2009932 0 2009932 0% /sys/firmware
Write a function df
that invokes the command df
, parses the output and returns the output as python values.
>>> df()
[
{'filesystem': 'overlay', 'blocks': 81106868, 'used': 7855576, 'available': 73234908, 'percent_used': 10, 'path': '/'},
{'filesystem': 'tmpfs', 'blocks': 65536, 'used': 0, 'available': 65536, 'percent_used': 0, 'path': '/dev'},
{'filesystem': 'shm', 'blocks': 65536, 'used': 0, 'available': 65536, 'percent_used': 0, 'path': '/dev/shm'},
{'filesystem': '/dev/vda1', 'blocks': 81106868, 'used': 7855576, 'available': 73234908, 'percent_used': 10, 'path': '/home'},
{'filesystem': 'tmpfs', 'blocks': 2009932, 'used': 0, 'available': 2009932, 'percent_used': 0, 'path': '/proc/acpi'},
{'filesystem': 'tmpfs', 'blocks': 2009932, 'used': 0, 'available': 2009932, 'percent_used': 0, 'path': '/proc/scsi'},
{'filesystem': 'tmpfs', 'blocks': 2009932, 'used': 0, 'available': 2009932, 'percent_used': 0, 'path': '/sys/firmware'}
]
Please note that the values of blocks
, used
, available
and percent_used
are integers.
Hints:
You can use the os.popen
command to run and command and read its output as a file.
>>> os.popen("seq 3").readlines()
['1\n', '2\n', '3\n']
In the above example, we are executing the command seq 3
and reading the output in Python.
Solution
import os
def parse_line(line):
fs, blocks, used, available, percent, path = line.strip().split()
return {
"filesystem": fs,
"blocks": int(blocks),
"used": int(used),
"available": int(available),
"percent_used": int(percent.strip("%")),
"path": path
}
def df():
lines = os.popen("df").readlines()
return [parse_line(line) for line in lines[1:]]