blob: 986d670319ffdf7feb3fec8d8f659aa8ea21400b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001#include <Python.h>
2
3int
4main(int argc, char *argv[])
5{
6 PyObject *pName, *pModule, *pDict, *pFunc;
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 Stinner25e014b2014-08-01 12:28:49 +020016 pName = PyUnicode_DecodeFSDefault(argv[1]);
Georg Brandl116aa622007-08-15 14:28:22 +000017 /* 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 Heimes217cfd12007-12-02 14:31:20 +000029 pValue = PyLong_FromLong(atoi(argv[i + 3]));
Georg Brandl116aa622007-08-15 14:28:22 +000030 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 Heimes217cfd12007-12-02 14:31:20 +000042 printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Georg Brandl116aa622007-08-15 14:28:22 +000043 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 }
66 Py_Finalize();
67 return 0;
68}