print to screen and file with one print statement

Mark McEahern marklists at mceahern.com
Wed Feb 12 16:24:06 EST 2003


[Mike Müller]
> This redirects all output from Python to the open file.
> At the same time I'd like to see all printed text on screen.
> How can I do this?

Same basic idea:

#!/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()

writer = MyWriter(sys.stdout, 'log.txt')
sys.stdout = writer

print 'test'

Cheers,

// m

-






More information about the Python-list mailing list