Created
May 20, 2012 08:52
-
-
Save oinume/2757398 to your computer and use it in GitHub Desktop.
Capture stdout in Python
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 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