Intercept and Tag STDOUT values

Andrew Durdin adurdin at
Wed Oct 13 07:20:37 CEST 2004

On Wed, 13 Oct 2004 04:06:54 GMT, Wes S.
<mornihatespamthdr at> wrote:
> class cStdOutRedirect :
>     stdOld = sys.stdout

You don't need this line -- that would try and save stdout when the
class is created, not when an instance is created.

>     def __main__(self) :

I believe you mean __init__, not __main__ (which is not a meaningful
method name)

>         self.stdOld = sys.stdout
>         sys.stdout = self
>         return True

Any return value from __init__ is never used, so there's no point having one.

>     def write(self,str) :

It's probably not a good idea to name a variable "str", as that will
override the builtin str() function.

>         self.stdOld.write("REDIRECTED OUTPUT: " + str)
>         return True

The write() function is not expected to return a value, so again omit it.

>     def close(self) :
>         sys.stdout = self.stdOld
>         return True

Ditto regarding return value for close().

With these changes, here's an example:

>>> class cStdOutRedirect(object):
...     def __init__(self):
...             self.stdOld = sys.stdout
...             sys.stdout = self
...     def write(self, s):
...             self.stdOld.write("REDIRECTED OUTPUT: " + s)
...     def close(self):
...             sys.stdout = self.stdOld
>>> import sys
>>> f = cStdOutRedirect()
>>> print "Hello"
>>> f.close()
>>> print "Hello"

This shows a couple of pitfalls: first, you might not want to have
stdout redirected as soon as the class is instantiated. Secondly, the
tag is put on every write() call, not just at the start of lines.
Thirdly, this may not work nicely if you try to redirect more than
once. Finally, you might need to override another few methods for
better compatibility (e.g. flush()).
I would also suggest renaming "close" to "end_redirect" or something,
as calling
    f = cStdOutRedirect()
comes across strangely.

More information about the Python-list mailing list