Writing to stdout and a log file

Mike mwakabayashi at gmail.com
Tue Apr 19 20:17:55 EDT 2005


I would like my 'print' statements to send its output to the user's
screen and a log file.

This is my initial attempt:

class StdoutLog(file):
    def __init__(self, stdout, name='/tmp/stdout.log',
mode='w',bufsize=-1):
        super(StdoutLog, self).__init__(name,mode,bufsize)
        self.stdout = stdout
    def write(self, data):
        self.stdout.write(data)
        self.write(data)

import sys
sys.stdout = StdoutLog(sys.stdout)
print 'STDOUT', sys.stdout

When the program is run the string is written to the log file but
nothing appears on my screen. Where's the screen output?

It looks like the superclass's write() method is getting called instead
of the StdoutLog instance's write() method.

The python documentation says 'print' should write to
sys.stdout.write() but that doesn't seem to be happening.

Any idea what's going one? 
Or ideas on how to debug this?

Thanks, Mike




More information about the Python-list mailing list