def change_cwd(directory):
    """ Change the current working dir """
    if not os.path.exists(directory):
        mess = "Cannot change working dir to '%s'\n" % directory
        mess += "This path does not exist"
        raise Exception(mess)
    previous_cwd = os.getcwd()
    os.chdir(directory)
    yield
    os.chdir(previous_cwd)