Search code examples
pythonwindowssamba

Available disk space on an SMB share, via Python


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

Solution

  • 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.