user596922 user596922 - 28 days ago 8
Python Question

Output on the console and file using python

I'm trying to find out a way in python to redirect the script execution log to a file as well as stdout in pythonic way. Is there any easy way of acheiving this?

Answer Source

I came up with this [untested]

import sys

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.flush() # If you want the output to be visible immediately
    def flush(self) :
        for f in self.files:

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test"  # This will go to stdout and the file out.txt

#use the original
sys.stdout = original
print "This won't appear on file"  # Only on stdout

print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.