views:

162

answers:

2

Does anyone know a way to get the amount of space available on a Windows (Samba) share via Python 2.6 with its standard library? (also running on Windows)

e.g.

>>> os.free_space("\\myshare\folder") # return free disk space, in bytes
1234567890
A: 

The standard library has the os.statvfs() function, but unfortunately it's only available on Unix-like platforms.

In case there is some cygwin-python maybe it would work there?

janneb
Unfortunately not, users only have a standard 2.5/2.6 Windows installation, nothing more.
Dave
@Dave: Well, no luck for you then. Though I suppose it shouldn't be too hard to cobble together something e.g. with the help of the standard subprocess module.
janneb
+3  A: 

If PyWin32 is available:

free, total, totalfree = win32file.GetDiskFreeSpaceEx(r'\\server\share')

Where free is a amount of free space available to the current user, and totalfree is amount of free space total. Relevant documentation: PyWin32 docs, MSDN.

If PyWin32 is not guaranteed to be available, then for Python 2.5 and higher there is ctypes module in stdlib. Same function, using ctypes:

import sys
from ctypes import *

c_ulonglong_p = POINTER(c_ulonglong)

_GetDiskFreeSpace = windll.kernel32.GetDiskFreeSpaceExW
_GetDiskFreeSpace.argtypes = [c_wchar_p, c_ulonglong_p, c_ulonglong_p, c_ulonglong_p]

def GetDiskFreeSpace(path):
    if not isinstance(path, unicode):
        path = path.decode('mbcs') # this is windows only code
    free, total, totalfree = c_ulonglong(0), c_ulonglong(0), c_ulonglong(0)
    if not _GetDiskFreeSpace(path, pointer(free), pointer(total), pointer(totalfree)):
        raise WindowsError
    return free.value, total.value, totalfree.value

Could probably be done better but I'm not really familiar with ctypes.

Zart