blob: 3afdd48269b1c67a70cd82d315c9a95e453dac69 [file] [log] [blame]
Fred Drakecc8f44b2001-08-20 19:30:29 +00001\chapter{Embedding Python in Another Application
2 \label{embedding}}
3
4The previous chapters discussed how to extend Python, that is, how to
5extend the functionality of Python by attaching a library of C
6functions to it. It is also possible to do it the other way around:
7enrich your C/\Cpp{} application by embedding Python in it. Embedding
8provides your application with the ability to implement some of the
9functionality of your application in Python rather than C or \Cpp.
10This can be used for many purposes; one example would be to allow
11users to tailor the application to their needs by writing some scripts
12in Python. You can also use it yourself if some of the functionality
13can be written in Python more easily.
14
15Embedding Python is similar to extending it, but not quite. The
16difference is that when you extend Python, the main program of the
17application is still the Python interpreter, while if you embed
18Python, the main program may have nothing to do with Python ---
19instead, some parts of the application occasionally call the Python
20interpreter to run some Python code.
21
22So if you are embedding Python, you are providing your own main
23program. One of the things this main program has to do is initialize
24the Python interpreter. At the very least, you have to call the
25function \cfunction{Py_Initialize()} (on Mac OS, call
26\cfunction{PyMac_Initialize()} instead). There are optional calls to
27pass command line arguments to Python. Then later you can call the
28interpreter from any part of the application.
29
30There are several different ways to call the interpreter: you can pass
31a string containing Python statements to
32\cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer
33and a file name (for identification in error messages only) to
34\cfunction{PyRun_SimpleFile()}. You can also call the lower-level
35operations described in the previous chapters to construct and use
36Python objects.
37
38A simple demo of embedding Python can be found in the directory
39\file{Demo/embed/} of the source distribution.
40
41
42\begin{seealso}
43 \seetitle[../api/api.html]{Python/C API Reference Manual}{The
44 details of Python's C interface are given in this manual.
45 A great deal of necessary information can be found here.}
46\end{seealso}
47
48
49\section{Very High Level Embedding
50 \label{high-level-embedding}}
51
52The simplest form of embedding Python is the use of the very
53high level interface. This interface is intended to execute a
54Python script without needing to interact with the application
55directly. This can for example be used to perform some operation
56on a file.
57
58\begin{verbatim}
59#include <Python.h>
60
61int main()
62{
63 Py_Initialize();
64 PyRun_SimpleString("from time import time,ctime\n"
65 "print 'Today is',ctime(time())\n");
66 Py_Finalize();
67 return 0;
68}
69\end{verbatim}
70
71The above code first initializes the Python interpreter with
72\cfunction{Py_Initialize()}, followed by the execution of a hard-coded
73Python script that print the date and time. Afterwards, the
74\cfunction{Py_Finalize()} call shuts the interpreter down, followed by
75the end of the program. In a real program, you may want to get the
76Python script from another source, perhaps a text-editor routine, a
77file, or a database. Getting the Python code from a file can better
78be done by using the \cfunction{PyRun_SimpleFile()} function, which
79saves you the trouble of allocating memory space and loading the file
80contents.
81
82
83\section{Beyond Very High Level Embedding: An overview
84 \label{lower-level-embedding}}
85
86The high level interface gives you the ability to execute
87arbitrary pieces of Python code from your application, but
88exchanging data values is quite cumbersome to say the least. If
89you want that, you should use lower level calls. At the cost of
90having to write more C code, you can achieve almost anything.
91
92It should be noted that extending Python and embedding Python
93is quite the same activity, despite the different intent. Most
94topics discussed in the previous chapters are still valid. To
95show this, consider what the extension code from Python to C
96really does:
97
98\begin{enumerate}
99 \item Convert data values from Python to C,
100 \item Perform a function call to a C routine using the
101 converted values, and
102 \item Convert the data values from the call from C to Python.
103\end{enumerate}
104
105When embedding Python, the interface code does:
106
107\begin{enumerate}
108 \item Convert data values from C to Python,
109 \item Perform a function call to a Python interface routine
110 using the converted values, and
111 \item Convert the data values from the call from Python to C.
112\end{enumerate}
113
114As you can see, the data conversion steps are simply swapped to
115accomodate the different direction of the cross-language transfer.
116The only difference is the routine that you call between both
117data conversions. When extending, you call a C routine, when
118embedding, you call a Python routine.
119
120This chapter will not discuss how to convert data from Python
121to C and vice versa. Also, proper use of references and dealing
122with errors is assumed to be understood. Since these aspects do not
123differ from extending the interpreter, you can refer to earlier
124chapters for the required information.
125
126
127\section{Pure Embedding
128 \label{pure-embedding}}
129
130The first program aims to execute a function in a Python
131script. Like in the section about the very high level interface,
132the Python interpreter does not directly interact with the
133application (but that will change in th next section).
134
135The code to run a function defined in a Python script is:
136
137\verbatiminput{run-func.c}
138
139This code loads a Python script using \code{argv[1]}, and calls the
140function named in \code{argv[2]}. Its integer arguments are the other
141values of the \code{argv} array. If you compile and link this
142program (let's call the finished executable \program{call}), and use
143it to execute a Python script, such as:
144
145\begin{verbatim}
146def multiply(a,b):
147 print "Thy shall add", a, "times", b
148 c = 0
149 for i in range(0, a):
150 c = c + b
151 return c
152\end{verbatim}
153
154then the result should be:
155
156\begin{verbatim}
157$ call multiply 3 2
158Thy shall add 3 times 2
159Result of call: 6
160\end{verbatim} % $
161
162Although the program is quite large for its functionality, most of the
163code is for data conversion between Python and C, and for error
164reporting. The interesting part with respect to embedding Python
165starts with
166
167\begin{verbatim}
168 Py_Initialize();
169 pName = PyString_FromString(argv[1]);
170 /* Error checking of pName left out */
171 pModule = PyImport_Import(pName);
172\end{verbatim}
173
174After initializing the interpreter, the script is loaded using
175\cfunction{PyImport_Import()}. This routine needs a Python string
176as its argument, which is constructed using the
177\cfunction{PyString_FromString()} data conversion routine.
178
179\begin{verbatim}
180 pDict = PyModule_GetDict(pModule);
181 /* pDict is a borrowed reference */
182
183 pFunc = PyDict_GetItemString(pDict, argv[2]);
184 /* pFun is a borrowed reference */
185
186 if (pFunc && PyCallable_Check(pFunc)) {
187 ...
188 }
189\end{verbatim}
190
191Once the script is loaded, its dictionary is retrieved with
192\cfunction{PyModule_GetDict()}. The dictionary is then searched using
193the normal dictionary access routines for the function name. If the
194name exists, and the object retunred is callable, you can safely
195assume that it is a function. The program then proceeds by
196constructing a tuple of arguments as normal. The call to the python
197function is then made with:
198
199\begin{verbatim}
200 pValue = PyObject_CallObject(pFunc, pArgs);
201\end{verbatim}
202
203Upon return of the function, \code{pValue} is either \NULL{} or it
204contains a reference to the return value of the function. Be sure to
205release the reference after examining the value.
206
207
208\section{Extending Embedded Python
209 \label{extending-with-embedding}}
210
211Until now, the embedded Python interpreter had no access to
212functionality from the application itself. The Python API allows this
213by extending the embedded interpreter. That is, the embedded
214interpreter gets extended with routines provided by the application.
215While it sounds complex, it is not so bad. Simply forget for a while
216that the application starts the Python interpreter. Instead, consider
217the application to be a set of subroutines, and write some glue code
218that gives Python access to those routines, just like you would write
219a normal Python extension. For example:
220
221\begin{verbatim}
222static int numargs=0;
223
224/* Return the number of arguments of the application command line */
225static PyObject*
226emb_numargs(PyObject *self, PyObject *args)
227{
228 if(!PyArg_ParseTuple(args, ":numargs"))
229 return NULL;
230 return Py_BuildValue("i", numargs);
231}
232
233static PyMethodDef EmbMethods[]={
234 {"numargs", emb_numargs, METH_VARARGS},
235 {NULL, NULL}
236};
237\end{verbatim}
238
239Insert the above code just above the \cfunction{main()} function.
240Also, insert the following two statements directly after
241\cfunction{Py_Initialize()}:
242
243\begin{verbatim}
244 numargs = argc;
245 Py_InitModule("emb", EmbMethods);
246\end{verbatim}
247
248These two lines initialize the \code{numargs} variable, and make the
249\function{emb.numargs()} function accessible to the embedded Python
250interpreter. With these extensions, the Python script can do things
251like
252
253\begin{verbatim}
254import emb
255print "Number of arguments", emb.numargs()
256\end{verbatim}
257
258In a real application, the methods will expose an API of the
259application to Python.
260
261
262%\section{For the future}
263%
264%You don't happen to have a nice library to get textual
265%equivalents of numeric values do you :-) ?
266%Callbacks here ? (I may be using information from that section
267%?!)
268%threads
269%code examples do not really behave well if errors happen
270% (what to watch out for)
271
272
273\section{Embedding Python in \Cpp{}
274 \label{embeddingInCplusplus}}
275
276It is also possible to embed Python in a \Cpp{} program; precisely how this
277is done will depend on the details of the \Cpp{} system used; in general you
278will need to write the main program in \Cpp{}, and use the \Cpp{} compiler
279to compile and link your program. There is no need to recompile Python
280itself using \Cpp{}.
281
282
283\section{Linking Requirements
284 \label{link-reqs}}
285
286While the \program{configure} script shipped with the Python sources
287will correctly build Python to export the symbols needed by
288dynamically linked extensions, this is not automatically inherited by
289applications which embed the Python library statically, at least on
290\UNIX. This is an issue when the application is linked to the static
291runtime library (\file{libpython.a}) and needs to load dynamic
292extensions (implemented as \file{.so} files).
293
294The problem is that some entry points are defined by the Python
295runtime solely for extension modules to use. If the embedding
296application does not use any of these entry points, some linkers will
297not include those entries in the symbol table of the finished
298executable. Some additional options are needed to inform the linker
299not to remove these symbols.
300
301Determining the right options to use for any given platform can be
302quite difficult, but fortunately the Python configuration already has
303those values. To retrieve them from an installed Python interpreter,
304start an interactive interpreter and have a short session like this:
305
306\begin{verbatim}
307>>> import distutils.sysconfig
308>>> distutils.sysconfig.get_config_var('LINKFORSHARED')
309'-Xlinker -export-dynamic'
310\end{verbatim}
311\refstmodindex{distutils.sysconfig}
312
313The contents of the string presented will be the options that should
314be used. If the string is empty, there's no need to add any
315additional options. The \constant{LINKFORSHARED} definition
316corresponds to the variable of the same name in Python's top-level
317\file{Makefile}.