[Tutor] Redirecting Python Interpreter Output

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 10 Aug 2002 19:44:50 -0700 (PDT)


On Sun, 11 Aug 2002, Ketut Mahaindra wrote:

> But now what if I want to catch the output from C++ ? Anybody got any
> experience on this ?
>
> So, for example I have a PyRun_SimpleString() or PyRun_SimpleFile or
> PyObject_CallObject on my C++ code ... Can I capture the output of the
> Python interpreter ?

Probably; what you can do is assign a file-like object to the 'sys.stdout'
variable of your embedded interpreter.  A StringIO.StringIO() instance
should do nicely.

Afterwards, once you allow the user to do a PyRun_SimpleString(), you can
pull out what was written to stdout by looking into the StringIO's
contents.

If you'd like, we can try to write a small sample application that does
this, although I've haven't played with embedding Python before!