Capturing print statements output

Sometimes you have code that has a lot of print statements, which are helping you with debugging. But what happens if you try to port that code to an environment without a console? In the best case, you won't see the prints anymore, in the worse case, the code will fail because there's no "valid file descriptor" to which to write.

The solution to this problem is to replace python's stdout file, which will enable the code output to be recorded and maybe logged for debugging purposes.

The following snippet shows how to achieve this:

>>> import StringIO, sys
>>> out = StringIO.StringIO()
>>> sys.stdout = out
>>> print "Test"
>>> log = out.getvalue()
>>> assert (log == "Test\n")
>>>


Comments