source: python/vendor/Python-2.7.6/Demo/embed/demo.c

Last change on this file was 388, checked in by dmik, 11 years ago

python: Update vendor to 2.7.6.

  • Property svn:eol-style set to native
File size: 2.1 KB
Line 
1/* Example of embedding Python in another program */
2
3#include "Python.h"
4
5void initxyzzy(void); /* Forward */
6
7main(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 leave it undefined (since the Python
20 code is generally not a main program it has no business
21 touching sys.argv...)
22
23 If the third argument is true, sys.path is modified to include
24 either the directory containing the script named by argv[0], or
25 the current working directory. This can be risky; if you run
26 an application embedding Python in a directory controlled by
27 someone else, attackers could put a Trojan-horse module in the
28 directory (say, a file named os.py) that your application would
29 then import and run.
30 */
31 PySys_SetArgvEx(argc, argv, 0);
32
33 /* Do some application specific code */
34 printf("Hello, brave new world\n\n");
35
36 /* Execute some Python statements (in module __main__) */
37 PyRun_SimpleString("import sys\n");
38 PyRun_SimpleString("print sys.builtin_module_names\n");
39 PyRun_SimpleString("print sys.modules.keys()\n");
40 PyRun_SimpleString("print sys.executable\n");
41 PyRun_SimpleString("print sys.argv\n");
42
43 /* Note that you can call any public function of the Python
44 interpreter here, e.g. call_object(). */
45
46 /* Some more application specific code */
47 printf("\nGoodbye, cruel world\n");
48
49 /* Exit, cleaning up the interpreter */
50 Py_Exit(0);
51 /*NOTREACHED*/
52}
53
54/* A static module */
55
56/* 'self' is not used */
57static PyObject *
58xyzzy_foo(PyObject *self, PyObject* args)
59{
60 return PyInt_FromLong(42L);
61}
62
63static PyMethodDef xyzzy_methods[] = {
64 {"foo", xyzzy_foo, METH_NOARGS,
65 "Return the meaning of everything."},
66 {NULL, NULL} /* sentinel */
67};
68
69void
70initxyzzy(void)
71{
72 PyImport_AddModule("xyzzy");
73 Py_InitModule("xyzzy", xyzzy_methods);
74}
Note: See TracBrowser for help on using the repository browser.