In article <[EMAIL PROTECTED]>, Just <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>, > Simo Melenius <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list