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