/Doc/includes/run-func.c

http://unladen-swallow.googlecode.com/ · C · 68 lines · 59 code · 6 blank · 3 comment · 13 complexity · bd8112c99013a995bd6e9ac8dc57f940 MD5 · raw file

  1. #include <Python.h>
  2. int
  3. main(int argc, char *argv[])
  4. {
  5. PyObject *pName, *pModule, *pDict, *pFunc;
  6. PyObject *pArgs, *pValue;
  7. int i;
  8. if (argc < 3) {
  9. fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
  10. return 1;
  11. }
  12. Py_Initialize();
  13. pName = PyString_FromString(argv[1]);
  14. /* Error checking of pName left out */
  15. pModule = PyImport_Import(pName);
  16. Py_DECREF(pName);
  17. if (pModule != NULL) {
  18. pFunc = PyObject_GetAttrString(pModule, argv[2]);
  19. /* pFunc is a new reference */
  20. if (pFunc && PyCallable_Check(pFunc)) {
  21. pArgs = PyTuple_New(argc - 3);
  22. for (i = 0; i < argc - 3; ++i) {
  23. pValue = PyInt_FromLong(atoi(argv[i + 3]));
  24. if (!pValue) {
  25. Py_DECREF(pArgs);
  26. Py_DECREF(pModule);
  27. fprintf(stderr, "Cannot convert argument\n");
  28. return 1;
  29. }
  30. /* pValue reference stolen here: */
  31. PyTuple_SetItem(pArgs, i, pValue);
  32. }
  33. pValue = PyObject_CallObject(pFunc, pArgs);
  34. Py_DECREF(pArgs);
  35. if (pValue != NULL) {
  36. printf("Result of call: %ld\n", PyInt_AsLong(pValue));
  37. Py_DECREF(pValue);
  38. }
  39. else {
  40. Py_DECREF(pFunc);
  41. Py_DECREF(pModule);
  42. PyErr_Print();
  43. fprintf(stderr,"Call failed\n");
  44. return 1;
  45. }
  46. }
  47. else {
  48. if (PyErr_Occurred())
  49. PyErr_Print();
  50. fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
  51. }
  52. Py_XDECREF(pFunc);
  53. Py_DECREF(pModule);
  54. }
  55. else {
  56. PyErr_Print();
  57. fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
  58. return 1;
  59. }
  60. Py_Finalize();
  61. return 0;
  62. }