blob: b5be5c6bf4ff8f14a0042cbaff33a62b96defb95 [file] [log] [blame]
Fred Drake53765752001-08-04 01:58:36 +00001#include <Python.h>
2
3int
4main(int argc, char *argv[])
5{
6 PyObject *pName, *pModule, *pDict, *pFunc;
7 PyObject *pArgs, *pValue;
Neal Norwitzae6bf4a2002-12-02 04:40:21 +00008 int i;
Fred Drake53765752001-08-04 01:58:36 +00009
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);
Neal Norwitz0f30dbd2002-12-17 00:40:38 +000020 Py_DECREF(pName);
21
Fred Drake53765752001-08-04 01:58:36 +000022 if (pModule != NULL) {
23 pDict = PyModule_GetDict(pModule);
24 /* pDict is a borrowed reference */
25
26 pFunc = PyDict_GetItemString(pDict, argv[2]);
27 /* pFun: Borrowed reference */
28
29 if (pFunc && PyCallable_Check(pFunc)) {
30 pArgs = PyTuple_New(argc - 3);
31 for (i = 0; i < argc - 3; ++i) {
32 pValue = PyInt_FromLong(atoi(argv[i + 3]));
33 if (!pValue) {
Neal Norwitz0f30dbd2002-12-17 00:40:38 +000034 Py_DECREF(pArgs);
35 Py_DECREF(pModule);
Fred Drake53765752001-08-04 01:58:36 +000036 fprintf(stderr, "Cannot convert argument\n");
37 return 1;
38 }
39 /* pValue reference stolen here: */
40 PyTuple_SetItem(pArgs, i, pValue);
41 }
42 pValue = PyObject_CallObject(pFunc, pArgs);
Neal Norwitz0f30dbd2002-12-17 00:40:38 +000043 Py_DECREF(pArgs);
Fred Drake53765752001-08-04 01:58:36 +000044 if (pValue != NULL) {
45 printf("Result of call: %ld\n", PyInt_AsLong(pValue));
46 Py_DECREF(pValue);
47 }
48 else {
Neal Norwitz0f30dbd2002-12-17 00:40:38 +000049 Py_DECREF(pModule);
Fred Drake53765752001-08-04 01:58:36 +000050 PyErr_Print();
51 fprintf(stderr,"Call failed\n");
52 return 1;
53 }
Fred Drake53765752001-08-04 01:58:36 +000054 /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
55 }
56 else {
Neal Norwitz0f30dbd2002-12-17 00:40:38 +000057 if (PyErr_Occurred())
58 PyErr_Print();
Fred Drake53765752001-08-04 01:58:36 +000059 fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
60 }
61 Py_DECREF(pModule);
62 }
63 else {
64 PyErr_Print();
65 fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
66 return 1;
67 }
Fred Drake53765752001-08-04 01:58:36 +000068 Py_Finalize();
69 return 0;
70}