redirect stdout python code example
Example 1: redirect stdout to variable python
from cStringIO import StringIO # Python3 use: from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
sys.stdout = old_stdout
# examine mystdout.getvalue()
Example 2: redirect python output to file
$ python foo.py > file