Source

python-utils / Tee.py

# Originally from http://stackoverflow.com/a/616686 add added the flush method

import sys

class Tee(object):
    def __init__(self, name, mode = 'w'):
        self.file = open(name, mode)
        self.stdout = sys.stdout
        sys.stdout = self
    def __del__(self):
        sys.stdout = self.stdout
        self.file.close()
    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)
    def flush(self):
        self.file.flush()
        self.stdout.flush()