embedding python interpreter
George Schlossnagle
george at omniti.com
Wed Nov 20 19:27:28 EST 2002
Hi,
I'm trying to embed a python interpreter into a c daemon to allow for
drop in python modules. What I have seems to work but doesn;t seem to
be the 'right' way to do it.
I allow two config options in my user config file, one for specifying a
module to import, and another that has a function which is the callback
called from the daemon.
I do my import as:
int python_import(char *module) {
PyObject *pModule, *pName;
pName = PyString_FromString(module);
pModule = PyImport_Import(pName);
if(pModule == NULL) {
fprintf(stderr, "Failed to load \"%s\"\n", module);
return NULL;
}
return 1;
}
(This is called from a lex/bison parsed config file once, the
interpeter is already started). Then on certain input, this callback
is called, with the function name (as module.name, since multiple
callbacks can be registered):
int python_log(char *func, char *sender, char *group, char *message) {
int retval;
char *ptr;
PyObject *pFunction, *pFunctionName, *pSender, *pGroup, *pMessage;
PyObject *pModuleName, *pDict, *pArgs;
pSender = PyString_FromString(sender);
pGroup = PyString_FromString(group);
pMessage = PyString_FromString(message);
ptr = strrchr(func, '.');
if(ptr == NULL) {
fprintf(stderr, "Function call must be <package>.<name>\n");
return NULL;
}
pFunctionName = PyString_FromString(ptr + 1);
pModuleName = PyString_FromStringAndSize(func, ptr - func);
pDict = PyModule_GetDict(PyImport_Import(pModuleName));
Py_DECREF(pModuleName);
if(pDict == NULL) {
return NULL;
}
pFunction = PyDict_GetItem(pDict, pFunctionName);
if(pFunction == NULL) {
fprintf(stderr, "Function not found\n");
return NULL;
}
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, pSender);
PyTuple_SetItem(pArgs, 1, pGroup);
PyTuple_SetItem(pArgs, 2, pMessage);
PyObjectCallObject(pFunction, pArgs);
Py_DECREF(pArgs);
return 1;
}
This seems to be the wrong way to find the correct PyDict object to get
pFunction from. It seems wrong to have to strrchr my function name to
get a module. It seems like there should be a way to get the symbol
table for my current scope.
It seems that this should be the acse, but I can't figure out how....
Any advice on doing this more correctly would be greatly appreciated.
Thanks!
George
More information about the Python-list
mailing list