Overriding sys.stdout

Bjorn Pettersen pbjorn at uswest.net
Thu Dec 21 05:12:25 CET 2000


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