Skip to content

Instantly share code, notes, and snippets.

@wcang
Created April 17, 2013 16:23
Show Gist options
  • Save wcang/5405652 to your computer and use it in GitHub Desktop.
Save wcang/5405652 to your computer and use it in GitHub Desktop.
Sample code to try out python's context manager.
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