| 1 |
#include "Python.h" |
|---|
| 2 |
|
|---|
| 3 |
void python_startup() { |
|---|
| 4 |
Py_SetProgramName("spreadlogd"); |
|---|
| 5 |
Py_Initialize(); |
|---|
| 6 |
} |
|---|
| 7 |
|
|---|
| 8 |
void python_shutdown() { |
|---|
| 9 |
Py_Exit(0); |
|---|
| 10 |
} |
|---|
| 11 |
|
|---|
| 12 |
int python_path(char *path) { |
|---|
| 13 |
PyObject *sys_dict, *sys_path; |
|---|
| 14 |
sys_dict = PyModule_GetDict(PyImport_Import(PyString_FromString("sys"))); |
|---|
| 15 |
sys_path = PyDict_GetItemString(sys_dict, "path"); |
|---|
| 16 |
PyList_Append(sys_path,PyString_FromString(path)); |
|---|
| 17 |
return 1; |
|---|
| 18 |
} |
|---|
| 19 |
|
|---|
| 20 |
int python_import(char *module) { |
|---|
| 21 |
PyObject *pModule, *pName; |
|---|
| 22 |
pName = PyString_FromString(module); |
|---|
| 23 |
pModule = PyImport_Import(pName); |
|---|
| 24 |
if(pModule == NULL) { |
|---|
| 25 |
fprintf(stderr, "Failed to load \"%s\"\n", module); |
|---|
| 26 |
return NULL; |
|---|
| 27 |
} |
|---|
| 28 |
return 1; |
|---|
| 29 |
} |
|---|
| 30 |
|
|---|
| 31 |
int python_log(char *func, char *sender, char *group, char *message) { |
|---|
| 32 |
int retval; |
|---|
| 33 |
char *ptr; |
|---|
| 34 |
PyObject *pFunction, *pFunctionName, *pSender, *pGroup, *pMessage; |
|---|
| 35 |
PyObject *pModuleName, *pDict, *pArgs; |
|---|
| 36 |
|
|---|
| 37 |
|
|---|
| 38 |
pSender = PyString_FromString(sender); |
|---|
| 39 |
pGroup = PyString_FromString(group); |
|---|
| 40 |
pMessage = PyString_FromString(message); |
|---|
| 41 |
ptr = strrchr(func, '.'); |
|---|
| 42 |
if(ptr == NULL) { |
|---|
| 43 |
fprintf(stderr, "Function call must be <package>.<name>\n"); |
|---|
| 44 |
return NULL; |
|---|
| 45 |
} |
|---|
| 46 |
pFunctionName = PyString_FromString(ptr + 1); |
|---|
| 47 |
pModuleName = PyString_FromStringAndSize(func, ptr - func); |
|---|
| 48 |
pDict = PyModule_GetDict(PyImport_Import(pModuleName)); |
|---|
| 49 |
Py_DECREF(pModuleName); |
|---|
| 50 |
if(pDict == NULL) { |
|---|
| 51 |
return NULL; |
|---|
| 52 |
} |
|---|
| 53 |
pFunction = PyDict_GetItem(pDict, pFunctionName); |
|---|
| 54 |
if(pFunction == NULL) { |
|---|
| 55 |
fprintf(stderr, "Function not found\n"); |
|---|
| 56 |
return NULL; |
|---|
| 57 |
} |
|---|
| 58 |
pArgs = PyTuple_New(2); |
|---|
| 59 |
PyTuple_SetItem(pArgs, 0, pSender); |
|---|
| 60 |
PyTuple_SetItem(pArgs, 1, pGroup); |
|---|
| 61 |
PyTuple_SetItem(pArgs, 2, pMessage); |
|---|
| 62 |
PyObjectCallObject(pFunction, pArgs); |
|---|
| 63 |
Py_DECREF(pArgs); |
|---|
| 64 |
return 1; |
|---|
| 65 |
} |
|---|
| 66 |
|
|---|