Skip to content

Instantly share code, notes, and snippets.

@oinume
Created May 20, 2012 08:52
Show Gist options
  • Save oinume/2757398 to your computer and use it in GitHub Desktop.
Save oinume/2757398 to your computer and use it in GitHub Desktop.
Capture stdout in Python
import cStringIO
import sys
class StdoutCapture(object):
def __init__(self):
self.captured = cStringIO.StringIO()
def start(self):
sys.stdout = self.captured
return self
def stop(self):
sys.stdout = sys.__stdout__
return self
def value(self):
self.captured.flush()
return self.captured.getvalue()
def close(self):
self.captured.close()
def __enter__(self):
return self.start()
def __exit__(self, type, value, traceback):
self.stop().close()
if __name__ == '__main__':
# Python >= 2.5
with StdoutCapture() as c:
print "This text is captured."
value = c.value()
print "captured: %s" % value
# Python < 2.5
c = StdoutCapture().start()
print "This text is captured."
value = c.value()
c.stop()
print "captured: %s" % (value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment