From 710e4c365709516186c5e193b31f2d925b7842bf Mon Sep 17 00:00:00 2001 From: neingeist Date: Thu, 24 Apr 2014 14:38:03 +0200 Subject: [PATCH] add with temporary_dir() example --- context-managers.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/context-managers.py b/context-managers.py index 083ffa6..93cb5eb 100755 --- a/context-managers.py +++ b/context-managers.py @@ -1,6 +1,13 @@ +#!/usr/bin/env python2.7 + +# Examples from: +# https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for + from contextlib import contextmanager -import os +from tempfile import mkdtemp +import os +import shutil @contextmanager def working_directory(path): @@ -21,9 +28,30 @@ def just_a_test(): print "finally!" + + +@contextmanager +def temporary_dir(*args, **kwds): + name = mkdtemp(*args, **kwds) + try: + yield name + finally: + shutil.rmtree(name) + + + with working_directory("/tmp"), just_a_test(): # do something within data/stuff print os.getcwd() # here I am back again in the original working directory print os.getcwd() + + +with temporary_dir() as tmpdir: + print tmpdir + tmpfile = tmpdir + "/foo" + with open(tmpfile, "w") as f: + f.write("foo") + +# tmpdir is now gone