Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Doc/includes/run-func.c
12 views
1
#define PY_SSIZE_T_CLEAN
2
#include <Python.h>
3
4
int
5
main(int argc, char *argv[])
6
{
7
PyObject *pName, *pModule, *pFunc;
8
PyObject *pArgs, *pValue;
9
int i;
10
11
if (argc < 3) {
12
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
13
return 1;
14
}
15
16
Py_Initialize();
17
pName = PyUnicode_DecodeFSDefault(argv[1]);
18
/* Error checking of pName left out */
19
20
pModule = PyImport_Import(pName);
21
Py_DECREF(pName);
22
23
if (pModule != NULL) {
24
pFunc = PyObject_GetAttrString(pModule, argv[2]);
25
/* pFunc is a new reference */
26
27
if (pFunc && PyCallable_Check(pFunc)) {
28
pArgs = PyTuple_New(argc - 3);
29
for (i = 0; i < argc - 3; ++i) {
30
pValue = PyLong_FromLong(atoi(argv[i + 3]));
31
if (!pValue) {
32
Py_DECREF(pArgs);
33
Py_DECREF(pModule);
34
fprintf(stderr, "Cannot convert argument\n");
35
return 1;
36
}
37
/* pValue reference stolen here: */
38
PyTuple_SetItem(pArgs, i, pValue);
39
}
40
pValue = PyObject_CallObject(pFunc, pArgs);
41
Py_DECREF(pArgs);
42
if (pValue != NULL) {
43
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
44
Py_DECREF(pValue);
45
}
46
else {
47
Py_DECREF(pFunc);
48
Py_DECREF(pModule);
49
PyErr_Print();
50
fprintf(stderr,"Call failed\n");
51
return 1;
52
}
53
}
54
else {
55
if (PyErr_Occurred())
56
PyErr_Print();
57
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
58
}
59
Py_XDECREF(pFunc);
60
Py_DECREF(pModule);
61
}
62
else {
63
PyErr_Print();
64
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
65
return 1;
66
}
67
if (Py_FinalizeEx() < 0) {
68
return 120;
69
}
70
return 0;
71
}
72
73