PyEval_EvalCodeEx return value

John Pinner funthyme at gmail.com
Tue Sep 20 10:40:06 EDT 2011


On Sep 20, 11:34 am, Mateusz Loskot <mate... at loskot.net> wrote:
> Hi,
>
> I'm trying to dig out details about what exactly is the return
> value the of PyEval_EvalCodeEx function in Python 3.x
> The documentation is sparse, unfortunately.
>
> Perhaps I'm looking at wrong function.
> My aim is simple, I need to execute Python code using Python interpreter
> embedded in my C++ application.
> The Python code is a simple script that always returns single value.
> For example:
>
> #! /usr/bin/env python
> def foo(a, b):
>     return a + b
> f = foo(2, 3)
>
> But, f can be of different type for different script: one returns
> numeric value, another returns a sequence, so the type is not
> possible to be determined in advance.
>
> I know how to capture Python stdout/stderr.
>
> I also know how to access the "f" attribute using
> PyObject_GetAttrString and then I can convert "f" value to C++ type
> depending on PyObject type.
>
> However, I guess there shall be a way to access "f" value
> directly from PyEval_EvalCode return object:
>
> PyObject* evalRet = ::PyEval_EvalCode(...);
>
> But, I can't find any details what the "evalRet" actually is.

I assume that you have read the documentation at http://docs.python.org/c-api/veryhigh.html,
and I agree that it's sparse, but the entry for the next entry,
PyEval_EvalCodeEx, tells you a little more, as does that for
PyEval_EvalFrameEx.

Obviously, it's returning a pointer to a PyObject, and Looking at the
source code, that may be NULL, to throw an exception, or an execution
frame, or a generator,etc, etc, depending on the code it's been given.
I guess that you should be able to inspect the PyObject to see what it
is.

What I'm wondering is, why are you eval-ing code ? A favourite device
of C programmers coming to Python (and mea culpa in the past), it's
fraught with potential problems and even security risks, and is
difficult to debug, and maybe you should be using introspection
instead.

And maybe you should be working in Python, and not C++ at this point,
do the dynamic stuff in the language best suited, and then return to C+
+ when needed.

Best wishes,

John
--

> Any pointers would be helpful.
>
> Best regards,
> --
> Mateusz Loskot,http://mateusz.loskot.net
> Charter Member of OSGeo,http://osgeo.org
> Member of ACCU,http://accu.org




More information about the Python-list mailing list