Available disk space on an SMB share, via Python
Question: 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
    


Answer: If [PyWin32](http://sourceforge.net/projects/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](http://docs.activestate.com/activepython/2.4/pywin32/win32file__GetDiskFreeSpaceEx_meth.html),
[MSDN](http://msdn.microsoft.com/en-us/library/aa364937%28VS.85%29.aspx).

If PyWin32 is not guaranteed to be available, then for Python 2.5 and higher
there is [ctypes module](http://docs.python.org/library/ctypes.html) 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.

