Created
April 17, 2013 16:23
-
-
Save wcang/5405652 to your computer and use it in GitHub Desktop.
Sample code to try out python's context manager.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
class cd: | |
def __init__(self, path): | |
print "constructor" | |
self.dest = path | |
self.origin = os.getcwd() | |
def __enter__(self): | |
os.chdir(self.dest) | |
print "Entering. Current working directory %s" % os.getcwd() | |
def __exit__(self, exc_type, exc_val, traceback): | |
if exc_type: | |
print "caught exception" | |
os.chdir(self.origin) | |
print "Exiting. Current working directory %s" % os.getcwd() | |
if __name__ == '__main__': | |
with cd("testdir"): | |
with open("test", "w") as f: | |
f.write("write something\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment