How to catch python's STDOUT

Peter Hansen peter at engcorp.com
Thu Apr 6 08:59:38 EDT 2006


Steven D'Aprano wrote:
>  >>> import sys, StringIO
>  >>> SAVEOUT = sys.stdout
>  >>> capture = StringIO.StringIO()
>  >>> sys.stdout = capture
>  >>> print "hello"
>  >>>
> 
> But be warned, I've had difficulty restoring stdout 
> afterwards, and needed to exit the interactive 
> interpreter to get things back to normal.

If you had difficulty, perhaps knowing about sys.__stdout__ would have 
helped... (?)  There's no need to preserve the original sys.stdout as 
you do above (in simple scripts, anyway) since Python does it for you. 
(Yes, in a library routine such as unittest you might need to do it in 
case the calling code has already modified it, but I doubt that's 
relevant in the OP's case.)

-Peter




More information about the Python-list mailing list