Writing to stdout and a log file

Wolfram Kraus kraus at hagen-partner.de
Wed Apr 20 03:10:33 EDT 2005


Mike wrote:
> 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)
What happens when you do a self.stdout.flush() here?

>         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
> 

I had the same problem (writing to file and stdout with print) and my 
solution was *not* to subclass file and instead add a 
self.outfile=file(...) to the constructor.

HTH,
Wolfram



More information about the Python-list mailing list