I'm using Python 2.6 on Linux. What is the fastest way:
to determine which partition contains a given directory or file?
For example, suppose that /dev/sda2
is mounted on /home
, and /dev/mapper/foo
is mounted on /home/foo
. From the string "/home/foo/bar/baz"
I would like to recover the pair ("/dev/mapper/foo", "home/foo")
.
and then, to get usage statistics of the given partition? For example, given /dev/mapper/foo
I would like to obtain the size of the partition and the free space available (either in bytes or approximately in megabytes).
If you just need the free space on a device, see the answer using os.statvfs()
below.
If you also need the device name and mount point associated with the file, you should call an external program to get this information. df
will provide all the information you need -- when called as df filename
it prints a line about the partition that contains the file.
To give an example:
import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
output.split("\n")[1].split()
Note that this is rather brittle, since it depends on the exact format of the df
output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc
filesystem below that are even less portable than this one.)