You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1019 B
Python
56 lines
1019 B
Python
11 years ago
|
#!/usr/bin/env python2.7
|
||
|
|
||
|
# Examples from:
|
||
|
# https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for
|
||
|
|
||
11 years ago
|
from contextlib import contextmanager
|
||
11 years ago
|
from tempfile import mkdtemp
|
||
11 years ago
|
|
||
11 years ago
|
import os
|
||
|
import shutil
|
||
11 years ago
|
|
||
11 years ago
|
|
||
11 years ago
|
@contextmanager
|
||
|
def working_directory(path):
|
||
|
current_dir = os.getcwd()
|
||
|
os.chdir(path)
|
||
|
try:
|
||
|
yield
|
||
|
finally:
|
||
|
os.chdir(current_dir)
|
||
|
|
||
|
|
||
|
@contextmanager
|
||
|
def just_a_test():
|
||
|
try:
|
||
|
print "just trying..."
|
||
|
yield
|
||
|
finally:
|
||
|
print "finally!"
|
||
|
|
||
|
|
||
11 years ago
|
@contextmanager
|
||
|
def temporary_dir(*args, **kwds):
|
||
|
name = mkdtemp(*args, **kwds)
|
||
|
try:
|
||
|
yield name
|
||
|
finally:
|
||
|
shutil.rmtree(name)
|
||
|
|
||
|
|
||
11 years ago
|
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()
|
||
11 years ago
|
|
||
|
|
||
|
with temporary_dir() as tmpdir:
|
||
|
print tmpdir
|
||
|
tmpfile = tmpdir + "/foo"
|
||
|
with open(tmpfile, "w") as f:
|
||
|
f.write("foo")
|
||
|
|
||
|
# tmpdir is now gone
|