04 Nov 2007

Redirecting stdout to StringIO object

So how do you redirect everything written to stdout and store it somewhere but also print it out to stdout? This was asked on #python and i answered it.

To access the stdout file object you need to import the sys module. Redirecting stdout to a StringIO object works because all functions that write to stdout expect the write() method of a file-like object, which StringIO has (along with read, seek etc). So here is the code;

So here is a quick breakdown line by line:

  • Lines 1 and 2 are used to import the required modules.

  • Then we subclass StringIO and create an attribute to hold the reference to stdout.

  • In Line 9 we overwrite the write method of the StringIO baseclass which does only one additional thing of writing back out to the original stdout, then it calls the baseclasses write method to store the string again.

  • Then also overwrite the read method that does one additional thing of seeking to the start of the StringIO object and then writing it all out back to stdout.