blob: 1546b1adcfa5659f8eb920a0f55697237c402ddb [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _embedding:
5
6***************************************
7Embedding Python in Another Application
8***************************************
9
10The previous chapters discussed how to extend Python, that is, how to extend the
11functionality of Python by attaching a library of C functions to it. It is also
12possible to do it the other way around: enrich your C/C++ application by
13embedding Python in it. Embedding provides your application with the ability to
14implement some of the functionality of your application in Python rather than C
15or C++. This can be used for many purposes; one example would be to allow users
16to tailor the application to their needs by writing some scripts in Python. You
17can also use it yourself if some of the functionality can be written in Python
18more easily.
19
20Embedding Python is similar to extending it, but not quite. The difference is
21that when you extend Python, the main program of the application is still the
22Python interpreter, while if you embed Python, the main program may have nothing
23to do with Python --- instead, some parts of the application occasionally call
24the Python interpreter to run some Python code.
25
26So if you are embedding Python, you are providing your own main program. One of
27the things this main program has to do is initialize the Python interpreter. At
Georg Brandl60203b42010-10-06 10:11:56 +000028the very least, you have to call the function :c:func:`Py_Initialize`. There are
Georg Brandlc575c902008-09-13 17:46:05 +000029optional calls to pass command line arguments to Python. Then later you can
30call the interpreter from any part of the application.
Georg Brandl116aa622007-08-15 14:28:22 +000031
32There are several different ways to call the interpreter: you can pass a string
Georg Brandl60203b42010-10-06 10:11:56 +000033containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a
Georg Brandl116aa622007-08-15 14:28:22 +000034stdio file pointer and a file name (for identification in error messages only)
Georg Brandl60203b42010-10-06 10:11:56 +000035to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations
Georg Brandl116aa622007-08-15 14:28:22 +000036described in the previous chapters to construct and use Python objects.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
39.. seealso::
40
41 :ref:`c-api-index`
42 The details of Python's C interface are given in this manual. A great deal of
43 necessary information can be found here.
44
45
46.. _high-level-embedding:
47
48Very High Level Embedding
49=========================
50
51The simplest form of embedding Python is the use of the very high level
52interface. This interface is intended to execute a Python script without needing
53to interact with the application directly. This can for example be used to
54perform some operation on a file. ::
55
56 #include <Python.h>
57
58 int
59 main(int argc, char *argv[])
60 {
Victor Stinner25e014b2014-08-01 12:28:49 +020061 wchar_t *program = Py_DecodeLocale(argv[0], NULL);
62 if (program == NULL) {
63 fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
64 exit(1);
65 }
66 Py_SetProgramName(program); /* optional but recommended */
67 Py_Initialize();
68 PyRun_SimpleString("from time import time,ctime\n"
69 "print('Today is', ctime(time()))\n");
Martin Panterb4ce1fc2015-11-30 03:18:29 +000070 if (Py_FinalizeEx() < 0) {
71 exit(120);
72 }
Victor Stinner25e014b2014-08-01 12:28:49 +020073 PyMem_RawFree(program);
74 return 0;
Georg Brandl116aa622007-08-15 14:28:22 +000075 }
76
Georg Brandl4552e3f2012-11-02 07:34:37 +010077The :c:func:`Py_SetProgramName` function should be called before
78:c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time
79libraries. Next, the Python interpreter is initialized with
80:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script
Martin Panterb4ce1fc2015-11-30 03:18:29 +000081that prints the date and time. Afterwards, the :c:func:`Py_FinalizeEx` call shuts
Georg Brandl4552e3f2012-11-02 07:34:37 +010082the interpreter down, followed by the end of the program. In a real program,
83you may want to get the Python script from another source, perhaps a text-editor
84routine, a file, or a database. Getting the Python code from a file can better
85be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the
86trouble of allocating memory space and loading the file contents.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
89.. _lower-level-embedding:
90
91Beyond Very High Level Embedding: An overview
92=============================================
93
94The high level interface gives you the ability to execute arbitrary pieces of
95Python code from your application, but exchanging data values is quite
96cumbersome to say the least. If you want that, you should use lower level calls.
97At the cost of having to write more C code, you can achieve almost anything.
98
99It should be noted that extending Python and embedding Python is quite the same
100activity, despite the different intent. Most topics discussed in the previous
101chapters are still valid. To show this, consider what the extension code from
102Python to C really does:
103
104#. Convert data values from Python to C,
105
106#. Perform a function call to a C routine using the converted values, and
107
108#. Convert the data values from the call from C to Python.
109
110When embedding Python, the interface code does:
111
112#. Convert data values from C to Python,
113
114#. Perform a function call to a Python interface routine using the converted
115 values, and
116
117#. Convert the data values from the call from Python to C.
118
119As you can see, the data conversion steps are simply swapped to accommodate the
120different direction of the cross-language transfer. The only difference is the
121routine that you call between both data conversions. When extending, you call a
122C routine, when embedding, you call a Python routine.
123
124This chapter will not discuss how to convert data from Python to C and vice
125versa. Also, proper use of references and dealing with errors is assumed to be
126understood. Since these aspects do not differ from extending the interpreter,
127you can refer to earlier chapters for the required information.
128
129
130.. _pure-embedding:
131
132Pure Embedding
133==============
134
135The first program aims to execute a function in a Python script. Like in the
136section about the very high level interface, the Python interpreter does not
137directly interact with the application (but that will change in the next
138section).
139
140The code to run a function defined in a Python script is:
141
142.. literalinclude:: ../includes/run-func.c
143
144
145This code loads a Python script using ``argv[1]``, and calls the function named
146in ``argv[2]``. Its integer arguments are the other values of the ``argv``
Antoine Pitrou71bca342011-11-30 21:19:21 +0100147array. If you :ref:`compile and link <compiling>` this program (let's call
148the finished executable :program:`call`), and use it to execute a Python
Ezio Melottia19ebdb2013-02-22 07:46:22 +0200149script, such as:
150
151.. code-block:: python
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153 def multiply(a,b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000154 print("Will compute", a, "times", b)
Georg Brandl116aa622007-08-15 14:28:22 +0000155 c = 0
156 for i in range(0, a):
157 c = c + b
158 return c
159
160then the result should be::
161
162 $ call multiply multiply 3 2
163 Will compute 3 times 2
164 Result of call: 6
165
166Although the program is quite large for its functionality, most of the code is
167for data conversion between Python and C, and for error reporting. The
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000168interesting part with respect to embedding Python starts with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 Py_Initialize();
Victor Stinner25e014b2014-08-01 12:28:49 +0200171 pName = PyUnicode_DecodeFSDefault(argv[1]);
Georg Brandl116aa622007-08-15 14:28:22 +0000172 /* Error checking of pName left out */
173 pModule = PyImport_Import(pName);
174
175After initializing the interpreter, the script is loaded using
Georg Brandl60203b42010-10-06 10:11:56 +0000176:c:func:`PyImport_Import`. This routine needs a Python string as its argument,
Georg Brandl3aa0c9d2012-07-01 09:43:20 +0200177which is constructed using the :c:func:`PyUnicode_FromString` data conversion
Georg Brandl116aa622007-08-15 14:28:22 +0000178routine. ::
179
180 pFunc = PyObject_GetAttrString(pModule, argv[2]);
181 /* pFunc is a new reference */
182
183 if (pFunc && PyCallable_Check(pFunc)) {
184 ...
185 }
186 Py_XDECREF(pFunc);
187
188Once the script is loaded, the name we're looking for is retrieved using
Georg Brandl60203b42010-10-06 10:11:56 +0000189:c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is
Georg Brandl116aa622007-08-15 14:28:22 +0000190callable, you can safely assume that it is a function. The program then
191proceeds by constructing a tuple of arguments as normal. The call to the Python
192function is then made with::
193
194 pValue = PyObject_CallObject(pFunc, pArgs);
195
196Upon return of the function, ``pValue`` is either *NULL* or it contains a
197reference to the return value of the function. Be sure to release the reference
198after examining the value.
199
200
201.. _extending-with-embedding:
202
203Extending Embedded Python
204=========================
205
206Until now, the embedded Python interpreter had no access to functionality from
207the application itself. The Python API allows this by extending the embedded
208interpreter. That is, the embedded interpreter gets extended with routines
209provided by the application. While it sounds complex, it is not so bad. Simply
210forget for a while that the application starts the Python interpreter. Instead,
211consider the application to be a set of subroutines, and write some glue code
212that gives Python access to those routines, just like you would write a normal
213Python extension. For example::
214
215 static int numargs=0;
216
217 /* Return the number of arguments of the application command line */
218 static PyObject*
219 emb_numargs(PyObject *self, PyObject *args)
220 {
221 if(!PyArg_ParseTuple(args, ":numargs"))
222 return NULL;
Georg Brandlc877a7c2010-11-26 11:55:48 +0000223 return PyLong_FromLong(numargs);
Georg Brandl116aa622007-08-15 14:28:22 +0000224 }
225
226 static PyMethodDef EmbMethods[] = {
227 {"numargs", emb_numargs, METH_VARARGS,
228 "Return the number of arguments received by the process."},
229 {NULL, NULL, 0, NULL}
230 };
231
Georg Brandl05b482c2008-12-07 22:45:56 +0000232 static PyModuleDef EmbModule = {
233 PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
234 NULL, NULL, NULL, NULL
235 };
236
Georg Brandlacc68cc2008-12-09 23:48:44 +0000237 static PyObject*
238 PyInit_emb(void)
239 {
240 return PyModule_Create(&EmbModule);
241 }
242
Georg Brandl60203b42010-10-06 10:11:56 +0000243Insert the above code just above the :c:func:`main` function. Also, insert the
244following two statements before the call to :c:func:`Py_Initialize`::
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246 numargs = argc;
Georg Brandlacc68cc2008-12-09 23:48:44 +0000247 PyImport_AppendInittab("emb", &PyInit_emb);
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249These two lines initialize the ``numargs`` variable, and make the
250:func:`emb.numargs` function accessible to the embedded Python interpreter.
Ezio Melottia19ebdb2013-02-22 07:46:22 +0200251With these extensions, the Python script can do things like
252
253.. code-block:: python
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255 import emb
Georg Brandl6911e3c2007-09-04 07:15:32 +0000256 print("Number of arguments", emb.numargs())
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258In a real application, the methods will expose an API of the application to
259Python.
260
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000261.. TODO: threads, code examples do not really behave well if errors happen
262 (what to watch out for)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264
265.. _embeddingincplusplus:
266
267Embedding Python in C++
268=======================
269
270It is also possible to embed Python in a C++ program; precisely how this is done
271will depend on the details of the C++ system used; in general you will need to
272write the main program in C++, and use the C++ compiler to compile and link your
273program. There is no need to recompile Python itself using C++.
274
275
Antoine Pitrou71bca342011-11-30 21:19:21 +0100276.. _compiling:
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Antoine Pitrou71bca342011-11-30 21:19:21 +0100278Compiling and Linking under Unix-like systems
279=============================================
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Antoine Pitrou71bca342011-11-30 21:19:21 +0100281It is not necessarily trivial to find the right flags to pass to your
282compiler (and linker) in order to embed the Python interpreter into your
283application, particularly because Python needs to load library modules
284implemented as C dynamic extensions (:file:`.so` files) linked against
285it.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Antoine Pitrou71bca342011-11-30 21:19:21 +0100287To find out the required compiler and linker flags, you can execute the
288:file:`python{X.Y}-config` script which is generated as part of the
Éric Araujo9c7b9192012-01-15 02:31:58 +0100289installation process (a :file:`python3-config` script may also be
Antoine Pitrou71bca342011-11-30 21:19:21 +0100290available). This script has several options, of which the following will
291be directly useful to you:
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Antoine Pitrou71bca342011-11-30 21:19:21 +0100293* ``pythonX.Y-config --cflags`` will give you the recommended flags when
294 compiling::
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Ned Deilye7b47dd2013-05-26 18:57:00 -0700296 $ /opt/bin/python3.4-config --cflags
297 -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
Antoine Pitrou71bca342011-11-30 21:19:21 +0100298
299* ``pythonX.Y-config --ldflags`` will give you the recommended flags when
300 linking::
301
Ned Deilye7b47dd2013-05-26 18:57:00 -0700302 $ /opt/bin/python3.4-config --ldflags
303 -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
Antoine Pitrou71bca342011-11-30 21:19:21 +0100304
305.. note::
306 To avoid confusion between several Python installations (and especially
307 between the system Python and your own compiled Python), it is recommended
308 that you use the absolute path to :file:`python{X.Y}-config`, as in the above
309 example.
310
311If this procedure doesn't work for you (it is not guaranteed to work for
Éric Araujo9c7b9192012-01-15 02:31:58 +0100312all Unix-like platforms; however, we welcome :ref:`bug reports <reporting-bugs>`)
313you will have to read your system's documentation about dynamic linking and/or
314examine Python's :file:`Makefile` (use :func:`sysconfig.get_makefile_filename`
315to find its location) and compilation
Antoine Pitrou71bca342011-11-30 21:19:21 +0100316options. In this case, the :mod:`sysconfig` module is a useful tool to
317programmatically extract the configuration values that you will want to
Ned Deily51cee7d2013-06-24 14:22:09 -0700318combine together. For example:
Ezio Melottia19ebdb2013-02-22 07:46:22 +0200319
320.. code-block:: python
Antoine Pitrou71bca342011-11-30 21:19:21 +0100321
322 >>> import sysconfig
Ned Deily51cee7d2013-06-24 14:22:09 -0700323 >>> sysconfig.get_config_var('LIBS')
324 '-lpthread -ldl -lutil'
Antoine Pitrou71bca342011-11-30 21:19:21 +0100325 >>> sysconfig.get_config_var('LINKFORSHARED')
Georg Brandl116aa622007-08-15 14:28:22 +0000326 '-Xlinker -export-dynamic'
327
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Antoine Pitrou71bca342011-11-30 21:19:21 +0100329.. XXX similar documentation for Windows missing