redirect standard output problem

Dave Angel d at
Fri Dec 21 15:36:44 CET 2012

On 12/21/2012 12:23 AM, iMath wrote:
> redirect standard output problem
> why the result only print A but leave out 888 ?
> import sys
> class RedirectStdoutTo:
>     def __init__(self, out_new):
>         self.out_new = out_new
>     def __enter__(self):
>         sys.stdout = self.out_new
>     def __exit__(self, *args):
>         sys.stdout = sys.__stdout__

Just a comment.  It'd be better to save and restore the stdout value,
rather than restoring it to what it was at begin of process.

Quoting from

It can also be used to restore the actual files to known working file
objects in case they have been overwritten with a broken object.
However, the preferred way to do this is to explicitly save the previous
stream before replacing it, and restore the saved object.

My reasoning is that some function further up the stack may also be
using a similar (or identical) redirection technique.  Anyway, instead
of using __stdout__, I'd use a saved value inside your object.

def __init__(self, out_new):
       self.out_new = out_new
def __enter__(self):
       self.savedstate = sys.stdout
      sys.stdout = self.out_new
def __exit__(self, *args):
      sys.stdout = self.savedstate

This may or may not solve your problem (I'd suspect that flush() is the
right answer), but I still think it's worth doing.



More information about the Python-list mailing list