Monday, May 21, 2012

Checking Hard Drive Space Using Python

Have you ever needed to check how much space is left on a drive, but didn't know how, well now you will.  Python ctypes and os libraries allow a developer to check the HD space pretty easily.  If you have a windows system, you can use ctypes to leverage the kernal32.dll functions, and if you have the other operating systems, python has a built in function called os.statvfs().


import ctypes
import platform
import os


class HardDriveSpaceException(Exception):
    def __init__(self, value):
        self.parameter = value
    def __str__(self):
        return repr(self.parameter)


def get_free_space(folder, format="MB"):
    """ 
        Return folder/drive free space 
    """
    fConstants = {"GB": 1073741824,
                  "MB": 1048576,
                  "KB": 1024,
                  "B": 1
                  }
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return (int(free_bytes.value/fConstants[format.upper()]), format)
    else:
        return (int(os.statvfs(folder).f_bfree*os.statvfs(folder).f_bsize/fConstants[format.upper()]), format)
if __name__ == "__main__":
    try:
        byteformat = "mb"
        size =  get_free_space(r"c:", byteformat)
        print size
        if size[0] < 10000000000:
            raise HardDriveSpaceException("Hard drive space limit reached, there is only %s %s space left." % (size[0],size[1]))
    except HardDriveSpaceException as e:
        print e

In this example, there is a function that checks your HD space, and a custom error. The custom error is raised if the numeric value is over a specific value.

I've tested the HD space function on Win7, Win7 x64, and Window Server 2008 R2 x64.  It works.  I don't have any OS's that aren't windows based, so let me know if it works on iOS or the other that some people use.

Some maybe wondering why would I want to do something like this.  Well, if you are creating content automatically, such as PDFs or any geospatial content, you want to ensure that you have the space to save it.

Enjoy