From 7a2dc23fd36ec6a6beab0163f1567f1cce93a970 Mon Sep 17 00:00:00 2001 From: Paul McCarthy <pauldmccarthy@gmail.com> Date: Sun, 10 Dec 2017 10:13:01 +1030 Subject: [PATCH] New module tempdir, which contains tempdir function --- fsl/utils/tempdir.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 fsl/utils/tempdir.py diff --git a/fsl/utils/tempdir.py b/fsl/utils/tempdir.py new file mode 100644 index 000000000..f17aa4482 --- /dev/null +++ b/fsl/utils/tempdir.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python +# +# tempdir.py - Utilities for working with temporary directories. +# +# Author: Paul McCarthy <pauldmccarthy@gmail.com> +# +"""This module contains utilities for working with temporary files and +directories. It currently only contains one function: + +.. autosummary:: + :nosignature: + + tempdir +""" + + +import os +import shutil +import tempfile +import contextlib + + +@contextlib.contextmanager +def tempdir(): + """Returns a context manager which creates and returns a temporary + directory, and then deletes it on exit. + """ + + testdir = tempfile.mkdtemp() + prevdir = os.getcwd() + try: + + os.chdir(testdir) + yield testdir + + finally: + os.chdir(prevdir) + shutil.rmtree(testdir) -- GitLab