We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?

In Python code, define an object with a write method that takes a single string argument. Assign this object to sys.stdout and sys.stderr. Then, the output will go wherever your write method sends it.

The easiest way to do this is to use the StringIO class in the standard library.

Sample code and use for catching stdout:

>>> class StdoutCatcher:
...     def __init__(self):
...         self.data = ''
...     def write(self, stuff):
...         self.data = self.data + stuff
>>> import sys
>>> old_stdout = sys.stdout
>>> sys.stdout = StdoutCatcher()
>>> print 'hello',
>>> print 'world!'
>>> sys.stderr.write(sys.stdout.data)
hello world!
>>> sys.stdout = old_stdout # restore
>>> print 'hello!'

If you want to use a C type instead, the type must provide both a write method and a writable softspace integer attribute to work properly with print.

CATEGORY: extending