[2] | 1 | .. highlightlang:: c
|
---|
| 2 |
|
---|
| 3 |
|
---|
| 4 | .. _embedding:
|
---|
| 5 |
|
---|
| 6 | ***************************************
|
---|
| 7 | Embedding Python in Another Application
|
---|
| 8 | ***************************************
|
---|
| 9 |
|
---|
| 10 | The previous chapters discussed how to extend Python, that is, how to extend the
|
---|
| 11 | functionality of Python by attaching a library of C functions to it. It is also
|
---|
| 12 | possible to do it the other way around: enrich your C/C++ application by
|
---|
| 13 | embedding Python in it. Embedding provides your application with the ability to
|
---|
| 14 | implement some of the functionality of your application in Python rather than C
|
---|
| 15 | or C++. This can be used for many purposes; one example would be to allow users
|
---|
| 16 | to tailor the application to their needs by writing some scripts in Python. You
|
---|
| 17 | can also use it yourself if some of the functionality can be written in Python
|
---|
| 18 | more easily.
|
---|
| 19 |
|
---|
| 20 | Embedding Python is similar to extending it, but not quite. The difference is
|
---|
| 21 | that when you extend Python, the main program of the application is still the
|
---|
| 22 | Python interpreter, while if you embed Python, the main program may have nothing
|
---|
| 23 | to do with Python --- instead, some parts of the application occasionally call
|
---|
| 24 | the Python interpreter to run some Python code.
|
---|
| 25 |
|
---|
| 26 | So if you are embedding Python, you are providing your own main program. One of
|
---|
| 27 | the things this main program has to do is initialize the Python interpreter. At
|
---|
[391] | 28 | the very least, you have to call the function :c:func:`Py_Initialize`. There are
|
---|
[2] | 29 | optional calls to pass command line arguments to Python. Then later you can
|
---|
| 30 | call the interpreter from any part of the application.
|
---|
| 31 |
|
---|
| 32 | There are several different ways to call the interpreter: you can pass a string
|
---|
[391] | 33 | containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a
|
---|
[2] | 34 | stdio file pointer and a file name (for identification in error messages only)
|
---|
[391] | 35 | to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations
|
---|
[2] | 36 | described in the previous chapters to construct and use Python objects.
|
---|
| 37 |
|
---|
| 38 | A simple demo of embedding Python can be found in the directory
|
---|
| 39 | :file:`Demo/embed/` of the source distribution.
|
---|
| 40 |
|
---|
| 41 |
|
---|
| 42 | .. seealso::
|
---|
| 43 |
|
---|
| 44 | :ref:`c-api-index`
|
---|
| 45 | The details of Python's C interface are given in this manual. A great deal of
|
---|
| 46 | necessary information can be found here.
|
---|
| 47 |
|
---|
| 48 |
|
---|
| 49 | .. _high-level-embedding:
|
---|
| 50 |
|
---|
| 51 | Very High Level Embedding
|
---|
| 52 | =========================
|
---|
| 53 |
|
---|
| 54 | The simplest form of embedding Python is the use of the very high level
|
---|
| 55 | interface. This interface is intended to execute a Python script without needing
|
---|
| 56 | to interact with the application directly. This can for example be used to
|
---|
| 57 | perform some operation on a file. ::
|
---|
| 58 |
|
---|
| 59 | #include <Python.h>
|
---|
| 60 |
|
---|
| 61 | int
|
---|
| 62 | main(int argc, char *argv[])
|
---|
| 63 | {
|
---|
[391] | 64 | Py_SetProgramName(argv[0]); /* optional but recommended */
|
---|
[2] | 65 | Py_Initialize();
|
---|
| 66 | PyRun_SimpleString("from time import time,ctime\n"
|
---|
| 67 | "print 'Today is',ctime(time())\n");
|
---|
| 68 | Py_Finalize();
|
---|
| 69 | return 0;
|
---|
| 70 | }
|
---|
| 71 |
|
---|
[391] | 72 | The :c:func:`Py_SetProgramName` function should be called before
|
---|
| 73 | :c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time
|
---|
| 74 | libraries. Next, the Python interpreter is initialized with
|
---|
| 75 | :c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script
|
---|
| 76 | that prints the date and time. Afterwards, the :c:func:`Py_Finalize` call shuts
|
---|
[2] | 77 | the interpreter down, followed by the end of the program. In a real program,
|
---|
| 78 | you may want to get the Python script from another source, perhaps a text-editor
|
---|
| 79 | routine, a file, or a database. Getting the Python code from a file can better
|
---|
[391] | 80 | be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the
|
---|
[2] | 81 | trouble of allocating memory space and loading the file contents.
|
---|
| 82 |
|
---|
| 83 |
|
---|
| 84 | .. _lower-level-embedding:
|
---|
| 85 |
|
---|
| 86 | Beyond Very High Level Embedding: An overview
|
---|
| 87 | =============================================
|
---|
| 88 |
|
---|
| 89 | The high level interface gives you the ability to execute arbitrary pieces of
|
---|
| 90 | Python code from your application, but exchanging data values is quite
|
---|
| 91 | cumbersome to say the least. If you want that, you should use lower level calls.
|
---|
| 92 | At the cost of having to write more C code, you can achieve almost anything.
|
---|
| 93 |
|
---|
| 94 | It should be noted that extending Python and embedding Python is quite the same
|
---|
| 95 | activity, despite the different intent. Most topics discussed in the previous
|
---|
| 96 | chapters are still valid. To show this, consider what the extension code from
|
---|
| 97 | Python to C really does:
|
---|
| 98 |
|
---|
| 99 | #. Convert data values from Python to C,
|
---|
| 100 |
|
---|
| 101 | #. Perform a function call to a C routine using the converted values, and
|
---|
| 102 |
|
---|
| 103 | #. Convert the data values from the call from C to Python.
|
---|
| 104 |
|
---|
| 105 | When embedding Python, the interface code does:
|
---|
| 106 |
|
---|
| 107 | #. Convert data values from C to Python,
|
---|
| 108 |
|
---|
| 109 | #. Perform a function call to a Python interface routine using the converted
|
---|
| 110 | values, and
|
---|
| 111 |
|
---|
| 112 | #. Convert the data values from the call from Python to C.
|
---|
| 113 |
|
---|
| 114 | As you can see, the data conversion steps are simply swapped to accommodate the
|
---|
| 115 | different direction of the cross-language transfer. The only difference is the
|
---|
| 116 | routine that you call between both data conversions. When extending, you call a
|
---|
| 117 | C routine, when embedding, you call a Python routine.
|
---|
| 118 |
|
---|
| 119 | This chapter will not discuss how to convert data from Python to C and vice
|
---|
| 120 | versa. Also, proper use of references and dealing with errors is assumed to be
|
---|
| 121 | understood. Since these aspects do not differ from extending the interpreter,
|
---|
| 122 | you can refer to earlier chapters for the required information.
|
---|
| 123 |
|
---|
| 124 |
|
---|
| 125 | .. _pure-embedding:
|
---|
| 126 |
|
---|
| 127 | Pure Embedding
|
---|
| 128 | ==============
|
---|
| 129 |
|
---|
| 130 | The first program aims to execute a function in a Python script. Like in the
|
---|
| 131 | section about the very high level interface, the Python interpreter does not
|
---|
| 132 | directly interact with the application (but that will change in the next
|
---|
| 133 | section).
|
---|
| 134 |
|
---|
| 135 | The code to run a function defined in a Python script is:
|
---|
| 136 |
|
---|
| 137 | .. literalinclude:: ../includes/run-func.c
|
---|
| 138 |
|
---|
| 139 |
|
---|
| 140 | This code loads a Python script using ``argv[1]``, and calls the function named
|
---|
| 141 | in ``argv[2]``. Its integer arguments are the other values of the ``argv``
|
---|
| 142 | array. If you compile and link this program (let's call the finished executable
|
---|
[391] | 143 | :program:`call`), and use it to execute a Python script, such as:
|
---|
[2] | 144 |
|
---|
[391] | 145 | .. code-block:: python
|
---|
| 146 |
|
---|
[2] | 147 | def multiply(a,b):
|
---|
| 148 | print "Will compute", a, "times", b
|
---|
| 149 | c = 0
|
---|
| 150 | for i in range(0, a):
|
---|
| 151 | c = c + b
|
---|
| 152 | return c
|
---|
| 153 |
|
---|
| 154 | then the result should be::
|
---|
| 155 |
|
---|
| 156 | $ call multiply multiply 3 2
|
---|
| 157 | Will compute 3 times 2
|
---|
| 158 | Result of call: 6
|
---|
| 159 |
|
---|
| 160 | Although the program is quite large for its functionality, most of the code is
|
---|
| 161 | for data conversion between Python and C, and for error reporting. The
|
---|
| 162 | interesting part with respect to embedding Python starts with ::
|
---|
| 163 |
|
---|
| 164 | Py_Initialize();
|
---|
| 165 | pName = PyString_FromString(argv[1]);
|
---|
| 166 | /* Error checking of pName left out */
|
---|
| 167 | pModule = PyImport_Import(pName);
|
---|
| 168 |
|
---|
| 169 | After initializing the interpreter, the script is loaded using
|
---|
[391] | 170 | :c:func:`PyImport_Import`. This routine needs a Python string as its argument,
|
---|
| 171 | which is constructed using the :c:func:`PyString_FromString` data conversion
|
---|
[2] | 172 | routine. ::
|
---|
| 173 |
|
---|
| 174 | pFunc = PyObject_GetAttrString(pModule, argv[2]);
|
---|
| 175 | /* pFunc is a new reference */
|
---|
| 176 |
|
---|
| 177 | if (pFunc && PyCallable_Check(pFunc)) {
|
---|
| 178 | ...
|
---|
| 179 | }
|
---|
| 180 | Py_XDECREF(pFunc);
|
---|
| 181 |
|
---|
| 182 | Once the script is loaded, the name we're looking for is retrieved using
|
---|
[391] | 183 | :c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is
|
---|
[2] | 184 | callable, you can safely assume that it is a function. The program then
|
---|
| 185 | proceeds by constructing a tuple of arguments as normal. The call to the Python
|
---|
| 186 | function is then made with::
|
---|
| 187 |
|
---|
| 188 | pValue = PyObject_CallObject(pFunc, pArgs);
|
---|
| 189 |
|
---|
| 190 | Upon return of the function, ``pValue`` is either *NULL* or it contains a
|
---|
| 191 | reference to the return value of the function. Be sure to release the reference
|
---|
| 192 | after examining the value.
|
---|
| 193 |
|
---|
| 194 |
|
---|
| 195 | .. _extending-with-embedding:
|
---|
| 196 |
|
---|
| 197 | Extending Embedded Python
|
---|
| 198 | =========================
|
---|
| 199 |
|
---|
| 200 | Until now, the embedded Python interpreter had no access to functionality from
|
---|
| 201 | the application itself. The Python API allows this by extending the embedded
|
---|
| 202 | interpreter. That is, the embedded interpreter gets extended with routines
|
---|
| 203 | provided by the application. While it sounds complex, it is not so bad. Simply
|
---|
| 204 | forget for a while that the application starts the Python interpreter. Instead,
|
---|
| 205 | consider the application to be a set of subroutines, and write some glue code
|
---|
| 206 | that gives Python access to those routines, just like you would write a normal
|
---|
| 207 | Python extension. For example::
|
---|
| 208 |
|
---|
| 209 | static int numargs=0;
|
---|
| 210 |
|
---|
| 211 | /* Return the number of arguments of the application command line */
|
---|
| 212 | static PyObject*
|
---|
| 213 | emb_numargs(PyObject *self, PyObject *args)
|
---|
| 214 | {
|
---|
| 215 | if(!PyArg_ParseTuple(args, ":numargs"))
|
---|
| 216 | return NULL;
|
---|
| 217 | return Py_BuildValue("i", numargs);
|
---|
| 218 | }
|
---|
| 219 |
|
---|
| 220 | static PyMethodDef EmbMethods[] = {
|
---|
| 221 | {"numargs", emb_numargs, METH_VARARGS,
|
---|
| 222 | "Return the number of arguments received by the process."},
|
---|
| 223 | {NULL, NULL, 0, NULL}
|
---|
| 224 | };
|
---|
| 225 |
|
---|
[391] | 226 | Insert the above code just above the :c:func:`main` function. Also, insert the
|
---|
| 227 | following two statements directly after :c:func:`Py_Initialize`::
|
---|
[2] | 228 |
|
---|
| 229 | numargs = argc;
|
---|
| 230 | Py_InitModule("emb", EmbMethods);
|
---|
| 231 |
|
---|
| 232 | These two lines initialize the ``numargs`` variable, and make the
|
---|
| 233 | :func:`emb.numargs` function accessible to the embedded Python interpreter.
|
---|
[391] | 234 | With these extensions, the Python script can do things like
|
---|
[2] | 235 |
|
---|
[391] | 236 | .. code-block:: python
|
---|
| 237 |
|
---|
[2] | 238 | import emb
|
---|
| 239 | print "Number of arguments", emb.numargs()
|
---|
| 240 |
|
---|
| 241 | In a real application, the methods will expose an API of the application to
|
---|
| 242 | Python.
|
---|
| 243 |
|
---|
| 244 | .. TODO: threads, code examples do not really behave well if errors happen
|
---|
| 245 | (what to watch out for)
|
---|
| 246 |
|
---|
| 247 |
|
---|
| 248 | .. _embeddingincplusplus:
|
---|
| 249 |
|
---|
| 250 | Embedding Python in C++
|
---|
| 251 | =======================
|
---|
| 252 |
|
---|
| 253 | It is also possible to embed Python in a C++ program; precisely how this is done
|
---|
| 254 | will depend on the details of the C++ system used; in general you will need to
|
---|
| 255 | write the main program in C++, and use the C++ compiler to compile and link your
|
---|
| 256 | program. There is no need to recompile Python itself using C++.
|
---|
| 257 |
|
---|
| 258 |
|
---|
| 259 | .. _link-reqs:
|
---|
| 260 |
|
---|
[391] | 261 | Compiling and Linking under Unix-like systems
|
---|
| 262 | =============================================
|
---|
[2] | 263 |
|
---|
[391] | 264 | It is not necessarily trivial to find the right flags to pass to your
|
---|
| 265 | compiler (and linker) in order to embed the Python interpreter into your
|
---|
| 266 | application, particularly because Python needs to load library modules
|
---|
| 267 | implemented as C dynamic extensions (:file:`.so` files) linked against
|
---|
| 268 | it.
|
---|
[2] | 269 |
|
---|
[391] | 270 | To find out the required compiler and linker flags, you can execute the
|
---|
| 271 | :file:`python{X.Y}-config` script which is generated as part of the
|
---|
| 272 | installation process (a :file:`python-config` script may also be
|
---|
| 273 | available). This script has several options, of which the following will
|
---|
| 274 | be directly useful to you:
|
---|
[2] | 275 |
|
---|
[391] | 276 | * ``pythonX.Y-config --cflags`` will give you the recommended flags when
|
---|
| 277 | compiling::
|
---|
[2] | 278 |
|
---|
[391] | 279 | $ /opt/bin/python2.7-config --cflags
|
---|
| 280 | -I/opt/include/python2.7 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
|
---|
| 281 |
|
---|
| 282 | * ``pythonX.Y-config --ldflags`` will give you the recommended flags when
|
---|
| 283 | linking::
|
---|
| 284 |
|
---|
| 285 | $ /opt/bin/python2.7-config --ldflags
|
---|
| 286 | -L/opt/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic
|
---|
| 287 |
|
---|
| 288 | .. note::
|
---|
| 289 | To avoid confusion between several Python installations (and especially
|
---|
| 290 | between the system Python and your own compiled Python), it is recommended
|
---|
| 291 | that you use the absolute path to :file:`python{X.Y}-config`, as in the above
|
---|
| 292 | example.
|
---|
| 293 |
|
---|
| 294 | If this procedure doesn't work for you (it is not guaranteed to work for
|
---|
| 295 | all Unix-like platforms; however, we welcome :ref:`bug reports <reporting-bugs>`)
|
---|
| 296 | you will have to read your system's documentation about dynamic linking and/or
|
---|
| 297 | examine Python's :file:`Makefile` (use :func:`sysconfig.get_makefile_filename`
|
---|
| 298 | to find its location) and compilation
|
---|
| 299 | options. In this case, the :mod:`sysconfig` module is a useful tool to
|
---|
| 300 | programmatically extract the configuration values that you will want to
|
---|
| 301 | combine together. For example:
|
---|
| 302 |
|
---|
| 303 | .. code-block:: python
|
---|
| 304 |
|
---|
| 305 | >>> import sysconfig
|
---|
| 306 | >>> sysconfig.get_config_var('LIBS')
|
---|
| 307 | '-lpthread -ldl -lutil'
|
---|
| 308 | >>> sysconfig.get_config_var('LINKFORSHARED')
|
---|
[2] | 309 | '-Xlinker -export-dynamic'
|
---|
| 310 |
|
---|
| 311 |
|
---|
[391] | 312 | .. XXX similar documentation for Windows missing
|
---|