Redirecting STDOUT to a Python Variable

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Jun 22 03:19:37 EDT 2010


On Mon, 21 Jun 2010 23:10:56 -0700, Anthony Papillion wrote:

> I'm writing an application that uses the Google Storage Python library. 
> When an error occurs, the error is printed on the terminal. What I need
> to do is intercept that text into a variable so I can run a re.search()
> against it and find out what's going on.

If the error is *only* printed to stdout (or stderr), then you can do 
this to capture it:


>>> import sys
>>> from StringIO import StringIO
>>> capture = StringIO()
>>> save_stdout = sys.stdout
>>> sys.stdout = capture
>>> print "hello world"
>>> sys.stdout = save_stdout
>>> print capture.getvalue()
hello world

>>>

Don't forget to restore stdout, or you'll have no end of grief later.


But if the error is a proper exception, and you're talking about the 
traceback, then wrap the call in a try...except block:


try:
    method(args)
except Exception, e:
    do_something_with(e)



-- 
Steven



More information about the Python-list mailing list