Can I redirect the stdout into some sort of string buffer? Can I redirect the stdout into some sort of string buffer? python python

Can I redirect the stdout into some sort of string buffer?


from cStringIO import StringIO # Python3 use: from io import StringIOimport sysold_stdout = sys.stdoutsys.stdout = mystdout = StringIO()# blah blah lots of code ...sys.stdout = old_stdout# examine mystdout.getvalue()


There is a contextlib.redirect_stdout() function in Python 3.4+:

import iofrom contextlib import redirect_stdoutwith io.StringIO() as buf, redirect_stdout(buf):    print('redirected')    output = buf.getvalue()

Here's a code example that shows how to implement it on older Python versions.


Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

This can be used to good effect to "catch" stdout output in a GUI application.

Here's a silly example in PyQt:

import sysfrom PyQt4 import QtGuiclass OutputWindow(QtGui.QPlainTextEdit):    def write(self, txt):        self.appendPlainText(str(txt))app = QtGui.QApplication(sys.argv)out = OutputWindow()sys.stdout=outout.show()print "hello world !"