redirecting stdout to a file as well as screen

SamG mad.vijay at gmail.com
Thu Apr 12 07:57:26 EDT 2007


On Apr 12, 3:42 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Thu, 12 Apr 2007 07:23:43 -0300, SamG <mad.vi... at gmail.com> escribió:
>
>
>
> >> >> > How could i make, from inside the program, to have the stdout and
> >> >> > stderr to be printed both to a file as well the terminal(as usual).
>
> >> >> class Tee(file):
> >> >>      others = ()
>
> >> >>      def write(self, data):
> >> >>          file.write(self, data)
> >> >>          for f in others:
> >> >>              f.write(data)
>
> >> > This is only creating an out.log file and all the stdout and stderr
> >> > are logged there.
>
> >> Sorry, `for f in others:` should read `for f in self.others:`
>
> > Does not make difference, does this work for you? Im working on linux.
> > But this code looks portable except for the file path :)
>
> Yes. And it's rather similar to your other example... Omit sys.stderr as
> Antoon Pardon suggested.
>
> --
> Gabriel Genellina


Thanks people i have got it working now...

with this program!

#END
import sys

class multicaster(object):
    def __init__(self, filelist):
        self.filelist = filelist

    def write(self, str):
        for f in self.filelist:
            f.write(str)

log_file=open('out.log','w')
mc = multicaster([sys.stderr, log_file])
sys.stdout = mc
sys.stderr = mc
sys.stdout.write( "Mojozoox\n")
sys.stderr.write( "Hello\n")
#END

works perfect for my needs.




More information about the Python-list mailing list