Skip to content
Snippets Groups Projects
Commit 4fce9451 authored by Paul McCarthy's avatar Paul McCarthy :mountain_bicyclist:
Browse files

tempdir has option to not change cwd.

parent 6ce64cfc
No related branches found
No related tags found
No related merge requests found
...@@ -21,22 +21,28 @@ import contextlib ...@@ -21,22 +21,28 @@ import contextlib
@contextlib.contextmanager @contextlib.contextmanager
def tempdir(root=None): def tempdir(root=None, changeto=True):
"""Returns a context manager which creates and returns a temporary """Returns a context manager which creates and returns a temporary
directory, and then deletes it on exit. directory, and then deletes it on exit.
:arg root: If provided, specifies a directroy in which to create the :arg root: If provided, specifies a directroy in which to create the
new temporary directory. Otherwise the system default is used new temporary directory. Otherwise the system default is
(see the ``tempfile.mkdtemp`` documentation). used (see the ``tempfile.mkdtemp`` documentation).
:arg changeto: If ``True`` (the default), current working directory is set
to the new temporary directory before yielding, and restored
afterwards.
""" """
testdir = tempfile.mkdtemp(dir=root) testdir = tempfile.mkdtemp(dir=root)
prevdir = os.getcwd() prevdir = os.getcwd()
try: try:
os.chdir(testdir) if changeto:
os.chdir(testdir)
yield testdir yield testdir
finally: finally:
os.chdir(prevdir) if changeto:
os.chdir(prevdir)
shutil.rmtree(testdir) shutil.rmtree(testdir)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment