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).
For the first point, you can try using
os.path.realpath
to get a canonical path, check it against/etc/mtab
(I'd actually suggest callinggetmntent
, but I can't find a normal way to access it) to find the longest match. (to be sure, you should probablystat
both the file and the presumed mountpoint to verify that they are in fact on the same device)For the second point, use
os.statvfs
to get block size and usage information.(Disclaimer: I have tested none of this, most of what I know came from the coreutils sources)
For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path,
disk_usage()
returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.Simple example from documentation:
Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.
Some sample pathnames on my computer:
PS
if on Python ≥3.3, there's
shutil.disk_usage(path)
which returns a named tuple of(total, used, free)
expressed in bytes.This doesn't give the name of the partition, but you can get the filesystem statistics directly using the
statvfs
Unix system call. To call it from Python, useos.statvfs('/home/foo/bar/baz')
.The relevant fields in the result, according to POSIX:
So to make sense of the values, multiply by
f_frsize
: