Overriding sys.stdout

John Q. Public at home.com
Fri Dec 22 01:30:54 CET 2000


Thank you for the help.  I can finally remove my hack from IDLE!

Jonathan Polley

jwpolley(a)collins(d)rockwell(d)com

Bjorn Pettersen wrote:

> Something like this should work...
>
> -- bjorn
>
> import StringIO
> import sys
>
> class Logger:
>  def __init__(self):
>   self.buffer = StringIO.StringIO()
>   self.save_stdout = sys.stdout
>  def close(self):
>   sys.stdout = self.save_stdout
>  def getvalue(self):
>   return self.buffer.getvalue()
>  def write(self,txt):
>   self.buffer.write(txt)
>   self.save_stdout.write(txt)
>
> >>> import log
> >>> import sys
> >>> l = log.Logger()
> >>> sys.stdout = l
> >>> print 5,6,7
> 5 6 7
> >>> print "hello %s" % "world"
> hello world
> >>> l.getvalue()
> '5 6 7\012hello world\012'
> >>> l.close()
>
> "John Q. Public" wrote:
>
> > I would like to be able to take a snapshot of stdout while a script is
> > running, but still allow stdout to be written to the terminal.  My
> > current, working, solution is to hack IDLE but I would like a generic
> > solution so we would not be bound to a specific IDE.  I would like to
> > use PythonWin on NT, if I can, or do the journaling in batch mode.
> >
> > My plan is to implement a class/module/whatever that I can used to
> > overwrite sys.stdout.  This class/module/whatever would write data to a
> > file and send it to the old stdout.  My mail questions are these:
> >
> >     Does such a class/module/whatever exist?
> >     If not, does anyone have an idea where I can start for info?  As a
> > last resort, I will start wading through IDLE and PythonWin, but I would
> > like some ideas first.
> >
> > Thanks!
> >
> > Jonathan Polley
> > jwpolley(a)collins(d)rockwell(d)com




More information about the Python-list mailing list