Issue 1577: shutil.move() where destination is a directory was doing a
[python.git] / Doc / extending / embedding.rst
blob95a30fef9f8970b02255d572852feef357eadc7e
1 .. highlightlang:: c
4 .. _embedding:
6 ***************************************
7 Embedding Python in Another Application
8 ***************************************
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.
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.
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
28 the very least, you have to call the function :cfunc:`Py_Initialize` (on Mac OS,
29 call :cfunc:`PyMac_Initialize` instead).  There are optional calls to pass
30 command line arguments to Python.  Then later you can call the interpreter from
31 any part of the application.
33 There are several different ways to call the interpreter: you can pass a string
34 containing Python statements to :cfunc:`PyRun_SimpleString`, or you can pass a
35 stdio file pointer and a file name (for identification in error messages only)
36 to :cfunc:`PyRun_SimpleFile`.  You can also call the lower-level operations
37 described in the previous chapters to construct and use Python objects.
39 A simple demo of embedding Python can be found in the directory
40 :file:`Demo/embed/` of the source distribution.
43 .. seealso::
45    :ref:`c-api-index`
46       The details of Python's C interface are given in this manual. A great deal of
47       necessary information can be found here.
50 .. _high-level-embedding:
52 Very High Level Embedding
53 =========================
55 The simplest form of embedding Python is the use of the very high level
56 interface. This interface is intended to execute a Python script without needing
57 to interact with the application directly. This can for example be used to
58 perform some operation on a file. ::
60    #include <Python.h>
62    int
63    main(int argc, char *argv[])
64    {
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    }
72 The above code first initializes the Python interpreter with
73 :cfunc:`Py_Initialize`, followed by the execution of a hard-coded Python script
74 that print the date and time.  Afterwards, the :cfunc:`Py_Finalize` call shuts
75 the interpreter down, followed by the end of the program.  In a real program,
76 you may want to get the Python script from another source, perhaps a text-editor
77 routine, a file, or a database.  Getting the Python code from a file can better
78 be done by using the :cfunc:`PyRun_SimpleFile` function, which saves you the
79 trouble of allocating memory space and loading the file contents.
82 .. _lower-level-embedding:
84 Beyond Very High Level Embedding: An overview
85 =============================================
87 The high level interface gives you the ability to execute arbitrary pieces of
88 Python code from your application, but exchanging data values is quite
89 cumbersome to say the least. If you want that, you should use lower level calls.
90 At the cost of having to write more C code, you can achieve almost anything.
92 It should be noted that extending Python and embedding Python is quite the same
93 activity, despite the different intent. Most topics discussed in the previous
94 chapters are still valid. To show this, consider what the extension code from
95 Python to C really does:
97 #. Convert data values from Python to C,
99 #. Perform a function call to a C routine using the converted values, and
101 #. Convert the data values from the call from C to Python.
103 When embedding Python, the interface code does:
105 #. Convert data values from C to Python,
107 #. Perform a function call to a Python interface routine using the converted
108    values, and
110 #. Convert the data values from the call from Python to C.
112 As you can see, the data conversion steps are simply swapped to accommodate the
113 different direction of the cross-language transfer. The only difference is the
114 routine that you call between both data conversions. When extending, you call a
115 C routine, when embedding, you call a Python routine.
117 This chapter will not discuss how to convert data from Python to C and vice
118 versa.  Also, proper use of references and dealing with errors is assumed to be
119 understood.  Since these aspects do not differ from extending the interpreter,
120 you can refer to earlier chapters for the required information.
123 .. _pure-embedding:
125 Pure Embedding
126 ==============
128 The first program aims to execute a function in a Python script. Like in the
129 section about the very high level interface, the Python interpreter does not
130 directly interact with the application (but that will change in the next
131 section).
133 The code to run a function defined in a Python script is:
135 .. literalinclude:: ../includes/run-func.c
138 This code loads a Python script using ``argv[1]``, and calls the function named
139 in ``argv[2]``.  Its integer arguments are the other values of the ``argv``
140 array.  If you compile and link this program (let's call the finished executable
141 :program:`call`), and use it to execute a Python script, such as::
143    def multiply(a,b):
144        print "Will compute", a, "times", b
145        c = 0
146        for i in range(0, a):
147            c = c + b
148        return c
150 then the result should be::
152    $ call multiply multiply 3 2
153    Will compute 3 times 2
154    Result of call: 6
156 Although the program is quite large for its functionality, most of the code is
157 for data conversion between Python and C, and for error reporting.  The
158 interesting part with respect to embedding Python starts with ::
160    Py_Initialize();
161    pName = PyString_FromString(argv[1]);
162    /* Error checking of pName left out */
163    pModule = PyImport_Import(pName);
165 After initializing the interpreter, the script is loaded using
166 :cfunc:`PyImport_Import`.  This routine needs a Python string as its argument,
167 which is constructed using the :cfunc:`PyString_FromString` data conversion
168 routine. ::
170    pFunc = PyObject_GetAttrString(pModule, argv[2]);
171    /* pFunc is a new reference */
173    if (pFunc && PyCallable_Check(pFunc)) {
174        ...
175    }
176    Py_XDECREF(pFunc);
178 Once the script is loaded, the name we're looking for is retrieved using
179 :cfunc:`PyObject_GetAttrString`.  If the name exists, and the object returned is
180 callable, you can safely assume that it is a function.  The program then
181 proceeds by constructing a tuple of arguments as normal.  The call to the Python
182 function is then made with::
184    pValue = PyObject_CallObject(pFunc, pArgs);
186 Upon return of the function, ``pValue`` is either *NULL* or it contains a
187 reference to the return value of the function.  Be sure to release the reference
188 after examining the value.
191 .. _extending-with-embedding:
193 Extending Embedded Python
194 =========================
196 Until now, the embedded Python interpreter had no access to functionality from
197 the application itself.  The Python API allows this by extending the embedded
198 interpreter.  That is, the embedded interpreter gets extended with routines
199 provided by the application. While it sounds complex, it is not so bad.  Simply
200 forget for a while that the application starts the Python interpreter.  Instead,
201 consider the application to be a set of subroutines, and write some glue code
202 that gives Python access to those routines, just like you would write a normal
203 Python extension.  For example::
205    static int numargs=0;
207    /* Return the number of arguments of the application command line */
208    static PyObject*
209    emb_numargs(PyObject *self, PyObject *args)
210    {
211        if(!PyArg_ParseTuple(args, ":numargs"))
212            return NULL;
213        return Py_BuildValue("i", numargs);
214    }
216    static PyMethodDef EmbMethods[] = {
217        {"numargs", emb_numargs, METH_VARARGS,
218         "Return the number of arguments received by the process."},
219        {NULL, NULL, 0, NULL}
220    };
222 Insert the above code just above the :cfunc:`main` function. Also, insert the
223 following two statements directly after :cfunc:`Py_Initialize`::
225    numargs = argc;
226    Py_InitModule("emb", EmbMethods);
228 These two lines initialize the ``numargs`` variable, and make the
229 :func:`emb.numargs` function accessible to the embedded Python interpreter.
230 With these extensions, the Python script can do things like ::
232    import emb
233    print "Number of arguments", emb.numargs()
235 In a real application, the methods will expose an API of the application to
236 Python.
238 .. TODO: threads, code examples do not really behave well if errors happen
239    (what to watch out for)
242 .. _embeddingincplusplus:
244 Embedding Python in C++
245 =======================
247 It is also possible to embed Python in a C++ program; precisely how this is done
248 will depend on the details of the C++ system used; in general you will need to
249 write the main program in C++, and use the C++ compiler to compile and link your
250 program.  There is no need to recompile Python itself using C++.
253 .. _link-reqs:
255 Linking Requirements
256 ====================
258 While the :program:`configure` script shipped with the Python sources will
259 correctly build Python to export the symbols needed by dynamically linked
260 extensions, this is not automatically inherited by applications which embed the
261 Python library statically, at least on Unix.  This is an issue when the
262 application is linked to the static runtime library (:file:`libpython.a`) and
263 needs to load dynamic extensions (implemented as :file:`.so` files).
265 The problem is that some entry points are defined by the Python runtime solely
266 for extension modules to use.  If the embedding application does not use any of
267 these entry points, some linkers will not include those entries in the symbol
268 table of the finished executable.  Some additional options are needed to inform
269 the linker not to remove these symbols.
271 Determining the right options to use for any given platform can be quite
272 difficult, but fortunately the Python configuration already has those values.
273 To retrieve them from an installed Python interpreter, start an interactive
274 interpreter and have a short session like this::
276    >>> import distutils.sysconfig
277    >>> distutils.sysconfig.get_config_var('LINKFORSHARED')
278    '-Xlinker -export-dynamic'
280 .. index:: module: distutils.sysconfig
282 The contents of the string presented will be the options that should be used.
283 If the string is empty, there's no need to add any additional options.  The
284 :const:`LINKFORSHARED` definition corresponds to the variable of the same name
285 in Python's top-level :file:`Makefile`.