Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)

Ron Garret rNOSPAMon at flownet.com
Mon Jan 3 10:41:32 EST 2005


In article <just-9BE0DB.10471903012005 at news1.news.xs4all.nl>,
 Just <just at xs4all.nl> wrote:

> In article <87u0py6elt.fsf at sme.intra.citec.fi>,
>  Simo Melenius <firstname.lastname at iki.fi-spam> wrote:
> 
> > I've sometimes replaced sys.stdout (and/or sys.stderr) to
> > capture/redirect debugging information in existing code that has
> > unwisely just "print"ed error and warning messages, instead of using
> > sys.stderr or error logging modules.
> > 
> > py> def with_output_to_string (func):
> > ...     try:
> > ...         sys.stdout = StringIO.StringIO ()
> > ...         func ()
> > ...         return sys.stdout.getvalue ()
> > ...     finally:
> > ...         sys.stdout = sys.__stdout__
> 
> Aargh, I can't believe how widespread this idiom is :-(. See my other 
> reply in this thread: DON'T use sys.__stdout__. Ever.

It's helpful to provide an explanation when saying things like this.

In this case, it's best to save the original value of sys.stdout and 
restore that, otherwise nested calls to with_output_to_string can fail, 
e.g.

def f():
  print 123

def g():
  print 456
  x = with_output_to_string(f)
  print 789

with_outupt_to_string(g)  # Will miss the 789

rg



More information about the Python-list mailing list