Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | #include <Python.h> |
| 2 | |
| 3 | int |
| 4 | main(int argc, char *argv[]) |
| 5 | { |
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి) | 62b6cea | 2018-06-28 11:55:20 +0530 | [diff] [blame] | 6 | PyObject *pName, *pModule, *pFunc; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | PyObject *pArgs, *pValue; |
| 8 | int i; |
| 9 | |
| 10 | if (argc < 3) { |
| 11 | fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); |
| 12 | return 1; |
| 13 | } |
| 14 | |
| 15 | Py_Initialize(); |
Victor Stinner | 25e014b | 2014-08-01 12:28:49 +0200 | [diff] [blame] | 16 | pName = PyUnicode_DecodeFSDefault(argv[1]); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | /* Error checking of pName left out */ |
| 18 | |
| 19 | pModule = PyImport_Import(pName); |
| 20 | Py_DECREF(pName); |
| 21 | |
| 22 | if (pModule != NULL) { |
| 23 | pFunc = PyObject_GetAttrString(pModule, argv[2]); |
| 24 | /* pFunc is a new reference */ |
| 25 | |
| 26 | if (pFunc && PyCallable_Check(pFunc)) { |
| 27 | pArgs = PyTuple_New(argc - 3); |
| 28 | for (i = 0; i < argc - 3; ++i) { |
Christian Heimes | 217cfd1 | 2007-12-02 14:31:20 +0000 | [diff] [blame] | 29 | pValue = PyLong_FromLong(atoi(argv[i + 3])); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 30 | if (!pValue) { |
| 31 | Py_DECREF(pArgs); |
| 32 | Py_DECREF(pModule); |
| 33 | fprintf(stderr, "Cannot convert argument\n"); |
| 34 | return 1; |
| 35 | } |
| 36 | /* pValue reference stolen here: */ |
| 37 | PyTuple_SetItem(pArgs, i, pValue); |
| 38 | } |
| 39 | pValue = PyObject_CallObject(pFunc, pArgs); |
| 40 | Py_DECREF(pArgs); |
| 41 | if (pValue != NULL) { |
Christian Heimes | 217cfd1 | 2007-12-02 14:31:20 +0000 | [diff] [blame] | 42 | printf("Result of call: %ld\n", PyLong_AsLong(pValue)); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | Py_DECREF(pValue); |
| 44 | } |
| 45 | else { |
| 46 | Py_DECREF(pFunc); |
| 47 | Py_DECREF(pModule); |
| 48 | PyErr_Print(); |
| 49 | fprintf(stderr,"Call failed\n"); |
| 50 | return 1; |
| 51 | } |
| 52 | } |
| 53 | else { |
| 54 | if (PyErr_Occurred()) |
| 55 | PyErr_Print(); |
| 56 | fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); |
| 57 | } |
| 58 | Py_XDECREF(pFunc); |
| 59 | Py_DECREF(pModule); |
| 60 | } |
| 61 | else { |
| 62 | PyErr_Print(); |
| 63 | fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); |
| 64 | return 1; |
| 65 | } |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 66 | if (Py_FinalizeEx() < 0) { |
| 67 | return 120; |
| 68 | } |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 69 | return 0; |
| 70 | } |