output to console and to multiple files

Matimus mccredie at gmail.com
Thu Feb 15 17:35:10 EST 2007


On Feb 15, 8:51 am, "Matimus" <mccre... at gmail.com> wrote:
> 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]

I tried this at lunch and it doesn't work. Some version of this method
may work, but Popen tries to call the 'fileno' method of the TeeFile
object (at least it did on my setup) and it isn't there. This is just
a preemptive warning before someone comes back to let me know my code
doesn't work.




More information about the Python-list mailing list