How to redirect stdout
Redirecting the Output Stream
# w w w . j a v a2 s .co m
import sys
sys.stdout = open('log.txt', 'a')
print 1
temp = sys.stdout
sys.stdout = open('log.txt', 'a')
print 'spam'
print 1, 2, 3
sys.stdout.close( )
sys.stdout = temp
print 'back here'
print open('log.txt').read( )