how to get the output of embedded python?

David Bolen db3l at fitlinxx.com
Thu Feb 15 02:16:04 CET 2001


Jean-Luc Fontaine <jfontain at winealley.com> writes:

> Yes. That is whatever output you would see when in interactive mode, if 
> that makes any sense...

Oh, I think I understand better.  You don't actually want to trap any
output generated during the execution of the code - you just want to
deal with the result of the expression you may be evaluating.

> That does not seem to matter in other scripting languages, such as Tcl or 
> Perl: calling an internal eval C function with a script as argument returns 
> the result of the script (not what comes out on stdout or stderr), which 
> may be empty.
> 
> For example, if I define a function foo that returns a string, invoking 
> eval("foo()") in C would return that string. Is not that the behavior of 
> python in interactive mode, for example?

On an expression by expression basis, yes, each expression has a
result object (but not statements such as "print" for example).

You should be able to handle the same thing from your controlling code
by dipping a little lower than the "Simple" high level functions.  By
using either PyRun_File or PyRun_String you can evaluate Python code,
and the result of the function is the resulting Python object (a
PyObject *).  Use PyEval_GetGlobals and PyEval_GetLocals for the
dictionaries to supply to the execution.

Once you have the resulting object pointer you can do anything you
want with it (using any of the Python functions available for
extending/embedding applications), including converting it into a
string representation if you like.  Note that the result does not
itself have to be a string object, since a Python expression can
result in any Python object.  Check out the abstract and concrete
objects layer in the C/API reference or the Python source for all
sorts of functions.

But if you know you want a string representation, you should be able
to use something like PyObject_Str to return a new Python object with
a string representation of the result object.  Then, if you just want
a char*, use PyString_AsString.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list