redirecting stdout to a file as well as screen
Antoon Pardon
apardon at forel.vub.ac.be
Thu Apr 12 05:53:25 EDT 2007
On 2007-04-12, SamG <mad.vijay at gmail.com> wrote:
> On Apr 12, 12:40 pm, "Ant" <ant... at gmail.com> wrote:
>> On Apr 12, 8:14 am, "SamG" <mad.vi... at gmail.com> wrote:
>>
>> > 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).
>>
>> One way would be to create a custom class which has the same methods
>> as the file type, and held a list of file-like objects to write to.
>> e.g.
>>
>> class multicaster(object):
>> def __init__(self, filelist):
>> self.filelist = filelist
>>
>> def write(self, str):
>> for f in self.filelist:
>> f.write(str)
>> def writelines(self, str_list):
>> #etc
>>
>> Then assign stdout and stderr to a new instance of one of these
>> objects:
>>
>> mc = multicaster([sys.stdout, sys.stderr, log_file])
>> sys.stdout = mc
>> sys.stderr = mc
>>
>> HTH
>
>
>
> I have written this....
>
> 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='out.log'
log_file is not a file but a string, So when you reach the
write method in your multicaster you get an atttribute error
because a string has no write method
> mc = multicaster([sys.stdout, sys.stderr, log_file])
Since sys.stdout and sys.stderr usually both refer to
the terminal, this will result in your output appearing
twice on the terminal
> sys.stdout = mc
> sys.stderr = mc
Maybe you are better of leaving sys.stderr as it is,
at least until you are sure your multicaster itself
is working as it should.
> print "Hello"
More information about the Python-list
mailing list