Can I redirect the stdout into some sort of string buffer?
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 !"