How to catch python's STDOUT

Steven D'Aprano steve at REMOVEMEcyber.com.au
Thu Apr 6 05:44:19 EDT 2006


praveenkumar.117 at gmail.com wrote:

> Hi,
>        Can someone help me by suggesting how to capture python's
> STDOUT. I doesn't want the python's output to get displayed on the
> screen.



 >>> 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.

Because I'm paranoid, I might prefer to leave
sys.stdout as it, and use a custom print
function which I control:

_CAPTURE = StringIO.StringIO()
_FLAG = True  # start capturing

def print(obj):
     global _CAPTURE, _FLAG
     if _FLAG:
         where = _CAPTURE
     else:
         where = sys.stdout
     print >>where, obj

Then I can start or stop capturing printing just by 
changing a flag.


-- 
Steven.




More information about the Python-list mailing list