output to console and to multiple files

Matimus mccredie at gmail.com
Thu Feb 15 11:51:46 EST 2007


On Feb 15, 7:53 am, "nathan.sh... at gmail.com" <nathan.sh... at gmail.com>
wrote:
> On Feb 14, 5:10 pm, "goodwolf" <Robert.Ka... at gmail.com> wrote:
>
>
>
> > like this?
>
> > class Writers (object):
>
> >     def __init__(self, *writers):
> >         self.writers = writers
>
> >     def write(self, string):
> >         for w in self.writers:
> >             w.write(string)
>
> >     def flush(self):
> >         for w in self.writers:
> >             w.flush():
>
> > import sys
>
> > logfile = open('log.txt', 'w')
> > sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile)
> > sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile)
>
> i've tried simliar methods to this and to what Matimus wrote. I know
> it works great when using print statements.
> However, I'm looking to find something that will work with the output
> from a subprocess, such as from spawn, os.system, os.popen, etc.

I think you should be able to use my or goodwolf's solution with the
subprocess module. Something like this (untested):

[code]
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__":
    import sys
    from subprocess import Popen

    command = "whatever you want to run"
    outf = file("log.out","w")
    errf = file("log.err","w")
    allf = file("log.txt","w")
    Popen(
        command,
        stdout = TeeFile(sys.__stdout__,outf,allf),
        stderr = TeeFile(sys.__stderr__,errf,allf)
    )
[/code]




More information about the Python-list mailing list