Evaluate a python expression from C?
Kragen Sitaker
kragen at pobox.com
Tue Nov 27 17:40:50 EST 2001
David Brady <daves_spam_dodging_account at yahoo.com> writes:
> Could the problem be the NULL args I pass in? For
> simple evaluation, what should I populate them with
> instead?
There were several problems; that was one of them. Here's an
apparently-working program, in C:
#include <stdio.h>
#include <Python.h>
void PyEval(char *data)
{
char *buf;
PyObject *globals, *locals, *pObj;
Py_Initialize();
globals = PyDict_New();
if (!globals) return;
locals = PyDict_New();
if (!locals) {
Py_DECREF(globals);
return;
}
// The following line doesn't access violate.
pObj = PyRun_String(data, Py_eval_input, globals, locals);
PyArg_ParseTuple(pObj, "s", &buf);
printf("%s", buf);
Py_DECREF(pObj);
Py_DECREF(globals);
Py_DECREF(locals);
}
int main(int argc, char **argv) {
PyEval(argv[1]);
}
I compiled it with
cc -g pyeval.c -Wall -I/usr/local/include/python2.1 -lpython2.1 -L/usr/local/lib/python2.1/config -o pyeval -ldl -lpthread -lm -lutil
which is somewhat system-dependent, and run it with
./pyeval '("hi\n",)'
(because, after all, PyArg_ParseTuple is expecting a tuple containing
a string)
More information about the Python-list
mailing list