demo.c 1.55 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2
/* Example of embedding Python in another program */

3
#include "Python.h"
Guido van Rossum's avatar
Guido van Rossum committed
4

5
void initxyzzy(void); /* Forward */
6

7
main(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
8
{
9 10
	/* Pass argv[0] to the Python interpreter */
	Py_SetProgramName(argv[0]);
Guido van Rossum's avatar
Guido van Rossum committed
11 12

	/* Initialize the Python interpreter.  Required. */
13
	Py_Initialize();
Guido van Rossum's avatar
Guido van Rossum committed
14

15 16 17
	/* Add a static module */
	initxyzzy();

Guido van Rossum's avatar
Guido van Rossum committed
18 19 20 21
	/* Define sys.argv.  It is up to the application if you
	   want this; you can also let it undefined (since the Python 
	   code is generally not a main program it has no business
	   touching sys.argv...) */
22
	PySys_SetArgv(argc, argv);
Guido van Rossum's avatar
Guido van Rossum committed
23 24 25 26 27

	/* Do some application specific code */
	printf("Hello, brave new world\n\n");

	/* Execute some Python statements (in module __main__) */
28 29
	PyRun_SimpleString("import sys\n");
	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");
Guido van Rossum's avatar
Guido van Rossum committed
33 34 35 36 37 38 39 40

	/* Note that you can call any public function of the Python
	   interpreter here, e.g. call_object(). */

	/* Some more application specific code */
	printf("\nGoodbye, cruel world\n");

	/* Exit, cleaning up the interpreter */
41
	Py_Exit(0);
Guido van Rossum's avatar
Guido van Rossum committed
42 43 44
	/*NOTREACHED*/
}

45 46
/* A static module */

47
/* 'self' is not used */
48
static PyObject *
49
xyzzy_foo(PyObject *self, PyObject* args)
50 51 52 53 54
{
	return PyInt_FromLong(42L);
}

static PyMethodDef xyzzy_methods[] = {
55 56
	{"foo",		xyzzy_foo,	METH_NOARGS,
	 "Return the meaning of everything."},
57 58 59 60
	{NULL,		NULL}		/* sentinel */
};

void
61
initxyzzy(void)
62 63 64 65
{
	PyImport_AddModule("xyzzy");
	Py_InitModule("xyzzy", xyzzy_methods);
}