output to console and to multiple files

Matimus mccredie at gmail.com
Wed Feb 14 19:05:37 EST 2007


I took a look around and I couldn't find anything either. I will be
keeping an eye on this thread to see if someone posts a more standard
solution. In the mean time though, I will offer up a potential
solution. Duck typing is your friend. If you are only using the write
method of your files, it can be pretty simple to implement a fake file
object to do what you want.

[code]
import sys

class TeeFile(object):
    def __init__(self,*files):
        self.files = files
    def write(self,txt):
        for fp in self.files:
            fp.write(txt)

if __name__ == "__main__":
    outf = file("log.out","w")
    errf = file("log.err","w")
    allf = file("log.txt","w")
    sys.stdout = TeeFile(sys.__stdout__,outf,allf)
    sys.stderr = TeeFile(sys.__stderr__,errf,allf)

    print "hello world this is stdout"
    print >> sys.stderr , "hello world this is stderr"
[/code]




More information about the Python-list mailing list