I would like to send my print statements to the terminal and to a log file at the same time. I can use redirect as describe in Dive into Python:
import sys
print 'Dive in' saveout = sys.stdout fsock = open('out.log', 'w') sys.stdout = fsock print 'This message will be logged but not displayed' print 'This message should be logged and also displayed' sys.stdout = saveout fsock.close()
This redirects all output from Python to the open file. At the same time I'd like to see all printed text on screen. How can I do this?
Mike Müller wrote: > I would like to send my print statements to the terminal and to a log > file at the same time. I can use redirect as describe in Dive into > Python:
> import sys
> print 'Dive in' > saveout = sys.stdout > fsock = open('out.log', 'w') > sys.stdout = fsock > print 'This message will be logged but not displayed' > print 'This message should be logged and also displayed' > sys.stdout = saveout > fsock.close()
> This redirects all output from Python to the open file. > At the same time I'd like to see all printed text on screen. > How can I do this?
works perfect. Just had to change ´file´ to ´open´ for my Python 2.1. Adding the method ´flush(self)´ to Writer helped to get my ´sys.stdout.flush()´ to work.