Context manager to temporarily replace sys.stdout and sys.stderr.

Either create a file object:

>>> out = open('somefile.txt', 'r')

or create a string stream:

>>> from cStringIO import StringIO
>>> out = StringIO()

and then use thus context manager to ensure that all stdout and stderr gets written to the desired output:

>>> with divert_stdout(out):
>>>     print 'Hello, world!'
replacement : string stream
Replacement string stream object - in practice, anything with a write method