views:

1661

answers:

3

Hey guys,

I'm looking for the number of free bytes on my HD, but have trouble doing so on python.

I've tried the following:

import os

stat = os.statvfs(path)
print stat.f_bsize * stat.f_bavail

But, on OS/X it gives me a 17529020874752 bytes, which is about about 1.6 TB, which would be very nice, but unfortunately not really true.

What's the best way to get to this figure?

A: 

What's wrong with

import subprocess
proc= subprocess.Popen( "df", stdout=subprocess.PIPE )
proc.stdout.read()
proc.wait()
S.Lott
Using straight Python means its OS agnostic. :)
PKKid
Its fragile as it relies on an external application to maintain constant formatting as opposed to a system library.
Shane C. Mason
It's not like the accepted answer is OS-agnostic either... my 2.6 installation on Windows doesn't have an `os.statvfs`.
romkyns
@Shane C. Mason: "relies on an external application". The external application is rigidly defined by the POSIX standard. It's as much as part of the OS as the libraries and will always be there.
S.Lott
+6  A: 

Try using f_frsize instead of f_bsize.

>>> s = os.statvfs('/')
>>> (s.f_bavail * s.f_frsize) / 1024
23836592L
>>> os.system('df -k /')
Filesystem   1024-blocks     Used Available Capacity  Mounted on
/dev/disk0s2   116884912 92792320  23836592    80%    /
Nicholas Riley
Thanks sir, that did the trick
Evert
A: 

It's not OS-independent, but this works on Linux, and probably on OS X as well:

print commands.getoutput('df .').split('\n')[1].split()[3]

How does it work? It gets the output of the 'df .' command, which gives you disk information about the partition of which the current directory is a part, splits it into two lines (just as it is printed to the screen), then takes the second line of that (by appending [1] after the first split()), then splits that line into different whitespace-separated pieces, and, finally, gives you the 4th element in that list.

>>> commands.getoutput('df .')
'Filesystem           1K-blocks      Used Available Use% Mounted on\n/dev/sda3             80416836  61324872  15039168  81% /'

>>> commands.getoutput('df .').split('\n')
['Filesystem           1K-blocks      Used Available Use% Mounted on', '/dev/sda3             80416836  61324908  15039132  81% /']

>>> commands.getoutput('df .').split('\n')[1]
'/dev/sda3             80416836  61324908  15039132  81% /'

>>> commands.getoutput('df .').split('\n')[1].split()
['/dev/sda3', '80416836', '61324912', '15039128', '81%', '/']

>>> commands.getoutput('df .').split('\n')[1].split()[3]
'15039128'

>>> print commands.getoutput('df .').split('\n')[1].split()[3]
15039128
elimisteve