Printing to screen and writing to a file at the same time
<p>I found some code online that generally works, but I want to use it multiple times in the same program (write different things to different files, while still printing to the screen the whole time). </p>

<p>That is to say, when it closes, I think sys.stdout closes, so printing at all, and using this class again fails. I tried reimporting sys, and other dumb stuff, but I can't get it to work.</p>

<p>Here's the site, and the code
groups.google.com/group/comp.lang.python/browse_thread/thread/d25a9f5608e473af/</p>

<pre><code>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' 
</code></pre>
