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).
The simplest way to find out it.
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 asdf filename
it prints a line about the partition that contains the file.To give an example:
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.)As of Python 3.3, there an easy and direct way to do this with the standard library:
These numbers are in bytes. See the documentation for more info.
Usually the
/proc
directory contains such information in Linux, it is a virtual filesystem. For example,/proc/mounts
gives information about current mounted disks; and you can parse it directly. Utilities liketop
,df
all make use of/proc
.I haven't used it, but this might help too, if you want a wrapper: http://bitbucket.org/chrismiles/psi/wiki/Home
This should make everything you asked:
On my box the code above prints: