f = open("a.txt", "w") f.write("hello") f.close() with open("a.txt", "w") as f: f.write("hello") f = open("a.txt") dir(f) import os class chdir: def __init__(self, dir): self.dir = dir print "__init__" def __enter__(self): print "__enter__" self.olddir = os.getcwd() os.chdir(self.dir) return self def __exit__(self, *a): print "__exit__" os.chdir(self.olddir) print os.getcwd() print "before with" with chdir("/tmp") as x: print os.getcwd() print "after with" print os.getcwd() import sys from StringIO import StringIO oldstdout = sys.stdout buf = StringIO() sys.stdout = buf print "hello" print "world" sys.stdout = oldstdout print "captured", repr(buf.getvalue()) # solution from StringIO import StringIO import sys class capture_output: def __init__(self): self.buf = StringIO() def __enter__(self): self.oldstdout = sys.stdout sys.stdout = self.buf return self.buf def __exit__(self, type, exc, traceback): sys.stdout = self.oldstdout #with capture_output() as buf: # print "hello" capture_output() print "hello" #out = buf.getvalue() #print "captured", repr(out) class ignore_exception: def __init__(self): pass def __enter__(self): pass def __exit__(self, type, exc, traceback): print type, exc, traceback return True with ignore_exception(): print "begin" raise IOError("fo")