Skip to content

Instantly share code, notes, and snippets.

@andrewsmedina
Created November 21, 2012 23:23
Show Gist options
  • Save andrewsmedina/4128516 to your computer and use it in GitHub Desktop.
Save andrewsmedina/4128516 to your computer and use it in GitHub Desktop.
custom context manager
import sys
from StringIO import StringIO
class redirect_stdout:
def __init__(self, target):
self.stdout = sys.stdout
self.target = target
def __enter__(self):
sys.stdout = self.target
def __exit__(self, type, value, tb):
sys.stdout = self.stdout
out = StringIO()
with redirect_stdout(out):
print "Test"
out.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment