Sunday, December 20, 2009

python: redirecting the output of "print" to both stdout and to a file

#!/usr/bin/env python

import sys

class MyWriter:

    def __init__(self, stdout, filename):
        self.stdout = stdout
        self.logfile = file(filename, 'a')

    def write(self, text):
        self.stdout.write(text)
        self.logfile.write(text)

    def close(self):
        self.stdout.close()
        self.logfile.close()

# create a writer object and test it out
writer = MyWriter(sys.stdout, 'log.txt')
sys.stdout = writer

print 'test' 
Works like a charm!

source