blob: 579ba0706e5414843688a2dbea9b57d546796361 [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
Guido van Rossum81e84c91997-12-25 04:51:41 +00005void initxyzzy(); /* Forward */
6
Guido van Rossum705d5171994-10-08 19:30:50 +00007main(argc, argv)
8 int argc;
9 char **argv;
10{
Guido van Rossum496bc7f1999-03-09 17:07:24 +000011 /* Pass argv[0] to the Python interpreter */
12 Py_SetProgramName(argv[0]);
Guido van Rossum705d5171994-10-08 19:30:50 +000013
14 /* Initialize the Python interpreter. Required. */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000015 Py_Initialize();
Guido van Rossum705d5171994-10-08 19:30:50 +000016
Guido van Rossum81e84c91997-12-25 04:51:41 +000017 /* Add a static module */
18 initxyzzy();
19
Guido van Rossum705d5171994-10-08 19:30:50 +000020 /* Define sys.argv. It is up to the application if you
21 want this; you can also let it undefined (since the Python
22 code is generally not a main program it has no business
23 touching sys.argv...) */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000024 PySys_SetArgv(argc, argv);
Guido van Rossum705d5171994-10-08 19:30:50 +000025
26 /* Do some application specific code */
27 printf("Hello, brave new world\n\n");
28
29 /* Execute some Python statements (in module __main__) */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000030 PyRun_SimpleString("import sys\n");
31 PyRun_SimpleString("print sys.builtin_module_names\n");
Guido van Rossum81e84c91997-12-25 04:51:41 +000032 PyRun_SimpleString("print sys.modules.keys()\n");
Guido van Rossum496bc7f1999-03-09 17:07:24 +000033 PyRun_SimpleString("print sys.executable\n");
Guido van Rossum3caad8c1995-03-28 09:22:53 +000034 PyRun_SimpleString("print sys.argv\n");
Guido van Rossum705d5171994-10-08 19:30:50 +000035
36 /* Note that you can call any public function of the Python
37 interpreter here, e.g. call_object(). */
38
39 /* Some more application specific code */
40 printf("\nGoodbye, cruel world\n");
41
42 /* Exit, cleaning up the interpreter */
Guido van Rossum3caad8c1995-03-28 09:22:53 +000043 Py_Exit(0);
Guido van Rossum705d5171994-10-08 19:30:50 +000044 /*NOTREACHED*/
45}
46
Guido van Rossum81e84c91997-12-25 04:51:41 +000047/* A static module */
48
49static PyObject *
50xyzzy_foo(self, args)
51 PyObject *self; /* Not used */
52 PyObject *args;
53{
54 if (!PyArg_ParseTuple(args, ""))
55 return NULL;
56 return PyInt_FromLong(42L);
57}
58
59static PyMethodDef xyzzy_methods[] = {
60 {"foo", xyzzy_foo, 1},
61 {NULL, NULL} /* sentinel */
62};
63
64void
65initxyzzy()
66{
67 PyImport_AddModule("xyzzy");
68 Py_InitModule("xyzzy", xyzzy_methods);
69}