@contextlib.contextmanager
def TemporaryDirectory(suffix='', prefix='tmp', base_path=None):
  temp_dir_path = tempfile.mkdtemp(suffix, prefix, base_path)
  try:
    yield temp_dir_path
  finally:
    try:
      shutil.rmtree(temp_dir_path)
    except OSError, e:
      if e.message == 'Cannot call rmtree on a symbolic link':
        # Interesting synthetic exception made up by shutil.rmtree.
        # Means we received a symlink from mkdtemp.
        # Also means must clean up the symlink instead.
        os.unlink(temp_dir_path)
      else:
        raise
A context manager to create a temporary directory and clean up on exit.
dataset/ETHPy150Open google/google-apputils/google/apputils/file_util.py/TemporaryDirectory