home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Demo / embed / demo.c next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  1.6 KB  |  67 lines

  1. /* Example of embedding Python in another program */
  2.  
  3. #include "Python.h"
  4.  
  5. void initxyzzy(void); /* Forward */
  6.  
  7. main(int argc, char **argv)
  8. {
  9.     /* Pass argv[0] to the Python interpreter */
  10.     Py_SetProgramName(argv[0]);
  11.  
  12.     /* Initialize the Python interpreter.  Required. */
  13.     Py_Initialize();
  14.  
  15.     /* Add a static module */
  16.     initxyzzy();
  17.  
  18.     /* Define sys.argv.  It is up to the application if you
  19.        want this; you can also let it undefined (since the Python 
  20.        code is generally not a main program it has no business
  21.        touching sys.argv...) */
  22.     PySys_SetArgv(argc, argv);
  23.  
  24.     /* Do some application specific code */
  25.     printf("Hello, brave new world\n\n");
  26.  
  27.     /* Execute some Python statements (in module __main__) */
  28.     PyRun_SimpleString("import sys\n");
  29.     PyRun_SimpleString("print sys.builtin_module_names\n");
  30.     PyRun_SimpleString("print sys.modules.keys()\n");
  31.     PyRun_SimpleString("print sys.executable\n");
  32.     PyRun_SimpleString("print sys.argv\n");
  33.  
  34.     /* Note that you can call any public function of the Python
  35.        interpreter here, e.g. call_object(). */
  36.  
  37.     /* Some more application specific code */
  38.     printf("\nGoodbye, cruel world\n");
  39.  
  40.     /* Exit, cleaning up the interpreter */
  41.     Py_Exit(0);
  42.     /*NOTREACHED*/
  43. }
  44.  
  45. /* A static module */
  46.  
  47. /* 'self' is not used */
  48. static PyObject *
  49. xyzzy_foo(PyObject *self, PyObjecT *args)
  50. {
  51.     if (!PyArg_ParseTuple(args, ""))
  52.         return NULL;
  53.     return PyInt_FromLong(42L);
  54. }
  55.  
  56. static PyMethodDef xyzzy_methods[] = {
  57.     {"foo",        xyzzy_foo,    1},
  58.     {NULL,        NULL}        /* sentinel */
  59. };
  60.  
  61. void
  62. initxyzzy(void)
  63. {
  64.     PyImport_AddModule("xyzzy");
  65.     Py_InitModule("xyzzy", xyzzy_methods);
  66. }
  67.