add some simple context manager aka "with" test
This commit is contained in:
parent
d0faaddc91
commit
9c52a332d8
1 changed files with 29 additions and 0 deletions
29
context-managers.py
Executable file
29
context-managers.py
Executable file
|
@ -0,0 +1,29 @@
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
@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!"
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
Loading…
Add table
Add a link
Reference in a new issue