add with temporary_dir() example
This commit is contained in:
parent
9c52a332d8
commit
710e4c3657
1 changed files with 30 additions and 2 deletions
|
@ -1,6 +1,13 @@
|
||||||
from contextlib import contextmanager
|
#!/usr/bin/env python2.7
|
||||||
import os
|
|
||||||
|
|
||||||
|
# Examples from:
|
||||||
|
# https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
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…
Add table
Add a link
Reference in a new issue