blob: 9a1883f2f4d01872dd73298eb3feddd9512ce0a7 [file] [log] [blame]
Guido van Rossum705d5171994-10-08 19:30:50 +00001/* Example of embedding Python in another program */
2
Guido van Rossum3caad8c1995-03-28 09:22:53 +00003#include "Python.h"
Guido van Rossum705d5171994-10-08 19:30:50 +00004
5static char *argv0;
6
Guido van Rossum81e84c91997-12-25 04:51:41 +00007void initxyzzy(); /* Forward */
8
Guido van Rossum705d5171994-10-08 19:30:50 +00009main(argc, argv)
10 int argc;
11 char **argv;
12{
13 /* Save a copy of argv0 */
14 argv0 = argv[0];
15
16 /* Initialize the Python interpreter. Required. */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000017 Py_Initialize();
Guido van Rossum705d5171994-10-08 19:30:50 +000018
Guido van Rossum81e84c91997-12-25 04:51:41 +000019 /* Add a static module */
20 initxyzzy();
21
Guido van Rossum705d5171994-10-08 19:30:50 +000022 /* Define sys.argv. It is up to the application if you
23 want this; you can also let it undefined (since the Python
24 code is generally not a main program it has no business
25 touching sys.argv...) */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000026 PySys_SetArgv(argc, argv);
Guido van Rossum705d5171994-10-08 19:30:50 +000027
28 /* Do some application specific code */
29 printf("Hello, brave new world\n\n");
30
31 /* Execute some Python statements (in module __main__) */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000032 PyRun_SimpleString("import sys\n");
33 PyRun_SimpleString("print sys.builtin_module_names\n");
Guido van Rossum81e84c91997-12-25 04:51:41 +000034 PyRun_SimpleString("print sys.modules.keys()\n");
Guido van Rossum3caad8c1995-03-28 09:22:53 +000035 PyRun_SimpleString("print sys.argv\n");
Guido van Rossum705d5171994-10-08 19:30:50 +000036
37 /* Note that you can call any public function of the Python
38 interpreter here, e.g. call_object(). */
39
40 /* Some more application specific code */
41 printf("\nGoodbye, cruel world\n");
42
43 /* Exit, cleaning up the interpreter */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000044 Py_Exit(0);
Guido van Rossum705d5171994-10-08 19:30:50 +000045 /*NOTREACHED*/
46}
47
Guido van Rossum3caad8c1995-03-28 09:22:53 +000048/* This function is called by the interpreter to get its own name */
Guido van Rossum705d5171994-10-08 19:30:50 +000049char *
50getprogramname()
51{
52 return argv0;
53}
Guido van Rossum81e84c91997-12-25 04:51:41 +000054
55/* A static module */
56
57static PyObject *
58xyzzy_foo(self, args)
59 PyObject *self; /* Not used */
60 PyObject *args;
61{
62 if (!PyArg_ParseTuple(args, ""))
63 return NULL;
64 return PyInt_FromLong(42L);
65}
66
67static PyMethodDef xyzzy_methods[] = {
68 {"foo", xyzzy_foo, 1},
69 {NULL, NULL} /* sentinel */
70};
71
72void
73initxyzzy()
74{
75 PyImport_AddModule("xyzzy");
76 Py_InitModule("xyzzy", xyzzy_methods);
77}