ยปCore Development>Code coverage>Demo/embed/demo.c

Python code coverage for Demo/embed/demo.c

#countcontent
1n/a/* Example of embedding Python in another program */
2n/a
3n/a#include "Python.h"
4n/a
5n/aPyObject* PyInit_xyzzy(void); /* Forward */
6n/a
7n/amain(int argc, char **argv)
8n/a{
9n/a /* Ignore passed-in argc/argv. If desired, conversion
10n/a should use mbstowcs to convert them. */
11n/a wchar_t *args[] = {L"embed", L"hello", 0};
12n/a
13n/a /* Pass argv[0] to the Python interpreter */
14n/a Py_SetProgramName(args[0]);
15n/a
16n/a /* Add a static module */
17n/a PyImport_AppendInittab("xyzzy", PyInit_xyzzy);
18n/a
19n/a /* Initialize the Python interpreter. Required. */
20n/a Py_Initialize();
21n/a
22n/a /* Define sys.argv. It is up to the application if you
23n/a want this; you can also leave it undefined (since the Python
24n/a code is generally not a main program it has no business
25n/a touching sys.argv...)
26n/a
27n/a If the third argument is true, sys.path is modified to include
28n/a either the directory containing the script named by argv[0], or
29n/a the current working directory. This can be risky; if you run
30n/a an application embedding Python in a directory controlled by
31n/a someone else, attackers could put a Trojan-horse module in the
32n/a directory (say, a file named os.py) that your application would
33n/a then import and run.
34n/a */
35n/a PySys_SetArgvEx(2, args, 0);
36n/a
37n/a /* Do some application specific code */
38n/a printf("Hello, brave new world\n\n");
39n/a
40n/a /* Execute some Python statements (in module __main__) */
41n/a PyRun_SimpleString("import sys\n");
42n/a PyRun_SimpleString("print(sys.builtin_module_names)\n");
43n/a PyRun_SimpleString("print(sys.modules.keys())\n");
44n/a PyRun_SimpleString("print(sys.executable)\n");
45n/a PyRun_SimpleString("print(sys.argv)\n");
46n/a
47n/a /* Note that you can call any public function of the Python
48n/a interpreter here, e.g. call_object(). */
49n/a
50n/a /* Some more application specific code */
51n/a printf("\nGoodbye, cruel world\n");
52n/a
53n/a /* Exit, cleaning up the interpreter */
54n/a Py_Exit(0);
55n/a /*NOTREACHED*/
56n/a}
57n/a
58n/a/* A static module */
59n/a
60n/a/* 'self' is not used */
61n/astatic PyObject *
62n/axyzzy_foo(PyObject *self, PyObject* args)
63n/a{
64n/a return PyLong_FromLong(42L);
65n/a}
66n/a
67n/astatic PyMethodDef xyzzy_methods[] = {
68n/a {"foo", xyzzy_foo, METH_NOARGS,
69n/a "Return the meaning of everything."},
70n/a {NULL, NULL} /* sentinel */
71n/a};
72n/a
73n/astatic struct PyModuleDef xyzzymodule = {
74n/a {}, /* m_base */
75n/a "xyzzy", /* m_name */
76n/a 0, /* m_doc */
77n/a 0, /* m_size */
78n/a xyzzy_methods, /* m_methods */
79n/a 0, /* m_reload */
80n/a 0, /* m_traverse */
81n/a 0, /* m_clear */
82n/a 0, /* m_free */
83n/a};
84n/a
85n/aPyObject*
86n/aPyInit_xyzzy(void)
87n/a{
88n/a return PyModule_Create(&xyzzymodule);
89n/a}