Fred Drake | 5376575 | 2001-08-04 01:58:36 +0000 | [diff] [blame] | 1 | #include <Python.h> |
| 2 | |
| 3 | int |
| 4 | main(int argc, char *argv[]) |
| 5 | { |
| 6 | PyObject *pName, *pModule, *pDict, *pFunc; |
| 7 | PyObject *pArgs, *pValue; |
| 8 | int i, result; |
| 9 | |
| 10 | if (argc < 3) { |
| 11 | fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); |
| 12 | return 1; |
| 13 | } |
| 14 | |
| 15 | Py_Initialize(); |
| 16 | pName = PyString_FromString(argv[1]); |
| 17 | /* Error checking of pName left out */ |
| 18 | |
| 19 | pModule = PyImport_Import(pName); |
| 20 | if (pModule != NULL) { |
| 21 | pDict = PyModule_GetDict(pModule); |
| 22 | /* pDict is a borrowed reference */ |
| 23 | |
| 24 | pFunc = PyDict_GetItemString(pDict, argv[2]); |
| 25 | /* pFun: Borrowed reference */ |
| 26 | |
| 27 | if (pFunc && PyCallable_Check(pFunc)) { |
| 28 | pArgs = PyTuple_New(argc - 3); |
| 29 | for (i = 0; i < argc - 3; ++i) { |
| 30 | pValue = PyInt_FromLong(atoi(argv[i + 3])); |
| 31 | if (!pValue) { |
| 32 | fprintf(stderr, "Cannot convert argument\n"); |
| 33 | return 1; |
| 34 | } |
| 35 | /* pValue reference stolen here: */ |
| 36 | PyTuple_SetItem(pArgs, i, pValue); |
| 37 | } |
| 38 | pValue = PyObject_CallObject(pFunc, pArgs); |
| 39 | if (pValue != NULL) { |
| 40 | printf("Result of call: %ld\n", PyInt_AsLong(pValue)); |
| 41 | Py_DECREF(pValue); |
| 42 | } |
| 43 | else { |
| 44 | PyErr_Print(); |
| 45 | fprintf(stderr,"Call failed\n"); |
| 46 | return 1; |
| 47 | } |
| 48 | Py_DECREF(pArgs); |
| 49 | /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ |
| 50 | } |
| 51 | else { |
| 52 | PyErr_Print(); |
| 53 | fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); |
| 54 | } |
| 55 | Py_DECREF(pModule); |
| 56 | } |
| 57 | else { |
| 58 | PyErr_Print(); |
| 59 | fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); |
| 60 | return 1; |
| 61 | } |
| 62 | Py_DECREF(pName); |
| 63 | Py_Finalize(); |
| 64 | return 0; |
| 65 | } |