Saturday, December 27, 2008

Embedding Python

I've finally written my first embedded Python program! The following is basically a "hello world" program that demonstrates the basics of writing a C program that interacts with Python. It starts the embedded Python environment, parses some input (which is stored in the __main__ namespace) and prints out that input directly from C.

#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
PyObject *globals, *list, *name, *item, *mp;
Py_ssize_t i, n;

Py_Initialize();
PyRun_SimpleString("a = 'some text'; b = 123.456");
mp = PyImport_AddModule("__main__");
list = PyObject_Dir(mp);
n = PyList_Size(list);
printf("n=%d\n", n);
for(i = 0; i < n; i++) {
name = PyList_GetItem(list, i);
item = PyObject_GetAttr(mp, name);
if(PyString_Check(item))
printf("list[%d] (string): '%s' = '%s'\n", i, PyString_AsString(name), PyString_AsString(item));
else if(PyFloat_Check(item))
printf("list[%d] (float): '%s' = %g\n", i, PyString_AsString(name), PyFloat_AsDouble(item));
}
Py_Finalize();

return 0;
}


To compile this program, you'll need to do something like
gcc embed_python.c -I/usr/include/python2.5 -lpython2.5

No comments: