add with temporary_dir() example

master
neingeist 11 years ago
parent 9c52a332d8
commit 710e4c3657

@ -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 from contextlib import contextmanager
import os from tempfile import mkdtemp
import os
import shutil
@contextmanager @contextmanager
def working_directory(path): def working_directory(path):
@ -21,9 +28,30 @@ def just_a_test():
print "finally!" 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(): with working_directory("/tmp"), just_a_test():
# do something within data/stuff # do something within data/stuff
print os.getcwd() print os.getcwd()
# here I am back again in the original working directory # here I am back again in the original working directory
print os.getcwd() 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

Loading…
Cancel
Save