Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/embedding.rst is written in an unsupported language. File is not indexed.

0001 .. _embedding:
0002 
0003 Embedding the interpreter
0004 #########################
0005 
0006 While pybind11 is mainly focused on extending Python using C++, it's also
0007 possible to do the reverse: embed the Python interpreter into a C++ program.
0008 All of the other documentation pages still apply here, so refer to them for
0009 general pybind11 usage. This section will cover a few extra things required
0010 for embedding.
0011 
0012 Getting started
0013 ===============
0014 
0015 A basic executable with an embedded interpreter can be created with just a few
0016 lines of CMake and the ``pybind11::embed`` target, as shown below. For more
0017 information, see :doc:`/compiling`.
0018 
0019 .. code-block:: cmake
0020 
0021     cmake_minimum_required(VERSION 3.4)
0022     project(example)
0023 
0024     find_package(pybind11 REQUIRED)  # or `add_subdirectory(pybind11)`
0025 
0026     add_executable(example main.cpp)
0027     target_link_libraries(example PRIVATE pybind11::embed)
0028 
0029 The essential structure of the ``main.cpp`` file looks like this:
0030 
0031 .. code-block:: cpp
0032 
0033     #include <pybind11/embed.h> // everything needed for embedding
0034     namespace py = pybind11;
0035 
0036     int main() {
0037         py::scoped_interpreter guard{}; // start the interpreter and keep it alive
0038 
0039         py::print("Hello, World!"); // use the Python API
0040     }
0041 
0042 The interpreter must be initialized before using any Python API, which includes
0043 all the functions and classes in pybind11. The RAII guard class ``scoped_interpreter``
0044 takes care of the interpreter lifetime. After the guard is destroyed, the interpreter
0045 shuts down and clears its memory. No Python functions can be called after this.
0046 
0047 Executing Python code
0048 =====================
0049 
0050 There are a few different ways to run Python code. One option is to use ``eval``,
0051 ``exec`` or ``eval_file``, as explained in :ref:`eval`. Here is a quick example in
0052 the context of an executable with an embedded interpreter:
0053 
0054 .. code-block:: cpp
0055 
0056     #include <pybind11/embed.h>
0057     namespace py = pybind11;
0058 
0059     int main() {
0060         py::scoped_interpreter guard{};
0061 
0062         py::exec(R"(
0063             kwargs = dict(name="World", number=42)
0064             message = "Hello, {name}! The answer is {number}".format(**kwargs)
0065             print(message)
0066         )");
0067     }
0068 
0069 Alternatively, similar results can be achieved using pybind11's API (see
0070 :doc:`/advanced/pycpp/index` for more details).
0071 
0072 .. code-block:: cpp
0073 
0074     #include <pybind11/embed.h>
0075     namespace py = pybind11;
0076     using namespace py::literals;
0077 
0078     int main() {
0079         py::scoped_interpreter guard{};
0080 
0081         auto kwargs = py::dict("name"_a="World", "number"_a=42);
0082         auto message = "Hello, {name}! The answer is {number}"_s.format(**kwargs);
0083         py::print(message);
0084     }
0085 
0086 The two approaches can also be combined:
0087 
0088 .. code-block:: cpp
0089 
0090     #include <pybind11/embed.h>
0091     #include <iostream>
0092 
0093     namespace py = pybind11;
0094     using namespace py::literals;
0095 
0096     int main() {
0097         py::scoped_interpreter guard{};
0098 
0099         auto locals = py::dict("name"_a="World", "number"_a=42);
0100         py::exec(R"(
0101             message = "Hello, {name}! The answer is {number}".format(**locals())
0102         )", py::globals(), locals);
0103 
0104         auto message = locals["message"].cast<std::string>();
0105         std::cout << message;
0106     }
0107 
0108 Importing modules
0109 =================
0110 
0111 Python modules can be imported using ``module_::import()``:
0112 
0113 .. code-block:: cpp
0114 
0115     py::module_ sys = py::module_::import("sys");
0116     py::print(sys.attr("path"));
0117 
0118 For convenience, the current working directory is included in ``sys.path`` when
0119 embedding the interpreter. This makes it easy to import local Python files:
0120 
0121 .. code-block:: python
0122 
0123     """calc.py located in the working directory"""
0124 
0125 
0126     def add(i, j):
0127         return i + j
0128 
0129 
0130 .. code-block:: cpp
0131 
0132     py::module_ calc = py::module_::import("calc");
0133     py::object result = calc.attr("add")(1, 2);
0134     int n = result.cast<int>();
0135     assert(n == 3);
0136 
0137 Modules can be reloaded using ``module_::reload()`` if the source is modified e.g.
0138 by an external process. This can be useful in scenarios where the application
0139 imports a user defined data processing script which needs to be updated after
0140 changes by the user. Note that this function does not reload modules recursively.
0141 
0142 .. _embedding_modules:
0143 
0144 Adding embedded modules
0145 =======================
0146 
0147 Embedded binary modules can be added using the ``PYBIND11_EMBEDDED_MODULE`` macro.
0148 Note that the definition must be placed at global scope. They can be imported
0149 like any other module.
0150 
0151 .. code-block:: cpp
0152 
0153     #include <pybind11/embed.h>
0154     namespace py = pybind11;
0155 
0156     PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
0157         // `m` is a `py::module_` which is used to bind functions and classes
0158         m.def("add", [](int i, int j) {
0159             return i + j;
0160         });
0161     }
0162 
0163     int main() {
0164         py::scoped_interpreter guard{};
0165 
0166         auto fast_calc = py::module_::import("fast_calc");
0167         auto result = fast_calc.attr("add")(1, 2).cast<int>();
0168         assert(result == 3);
0169     }
0170 
0171 Unlike extension modules where only a single binary module can be created, on
0172 the embedded side an unlimited number of modules can be added using multiple
0173 ``PYBIND11_EMBEDDED_MODULE`` definitions (as long as they have unique names).
0174 
0175 These modules are added to Python's list of builtins, so they can also be
0176 imported in pure Python files loaded by the interpreter. Everything interacts
0177 naturally:
0178 
0179 .. code-block:: python
0180 
0181     """py_module.py located in the working directory"""
0182     import cpp_module
0183 
0184     a = cpp_module.a
0185     b = a + 1
0186 
0187 
0188 .. code-block:: cpp
0189 
0190     #include <pybind11/embed.h>
0191     namespace py = pybind11;
0192 
0193     PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
0194         m.attr("a") = 1;
0195     }
0196 
0197     int main() {
0198         py::scoped_interpreter guard{};
0199 
0200         auto py_module = py::module_::import("py_module");
0201 
0202         auto locals = py::dict("fmt"_a="{} + {} = {}", **py_module.attr("__dict__"));
0203         assert(locals["a"].cast<int>() == 1);
0204         assert(locals["b"].cast<int>() == 2);
0205 
0206         py::exec(R"(
0207             c = a + b
0208             message = fmt.format(a, b, c)
0209         )", py::globals(), locals);
0210 
0211         assert(locals["c"].cast<int>() == 3);
0212         assert(locals["message"].cast<std::string>() == "1 + 2 = 3");
0213     }
0214 
0215 
0216 Interpreter lifetime
0217 ====================
0218 
0219 The Python interpreter shuts down when ``scoped_interpreter`` is destroyed. After
0220 this, creating a new instance will restart the interpreter. Alternatively, the
0221 ``initialize_interpreter`` / ``finalize_interpreter`` pair of functions can be used
0222 to directly set the state at any time.
0223 
0224 Modules created with pybind11 can be safely re-initialized after the interpreter
0225 has been restarted. However, this may not apply to third-party extension modules.
0226 The issue is that Python itself cannot completely unload extension modules and
0227 there are several caveats with regard to interpreter restarting. In short, not
0228 all memory may be freed, either due to Python reference cycles or user-created
0229 global data. All the details can be found in the CPython documentation.
0230 
0231 .. warning::
0232 
0233     Creating two concurrent ``scoped_interpreter`` guards is a fatal error. So is
0234     calling ``initialize_interpreter`` for a second time after the interpreter
0235     has already been initialized.
0236 
0237     Do not use the raw CPython API functions ``Py_Initialize`` and
0238     ``Py_Finalize`` as these do not properly handle the lifetime of
0239     pybind11's internal data.
0240 
0241 
0242 Sub-interpreter support
0243 =======================
0244 
0245 Creating multiple copies of ``scoped_interpreter`` is not possible because it
0246 represents the main Python interpreter. Sub-interpreters are something different
0247 and they do permit the existence of multiple interpreters. This is an advanced
0248 feature of the CPython API and should be handled with care. pybind11 does not
0249 currently offer a C++ interface for sub-interpreters, so refer to the CPython
0250 documentation for all the details regarding this feature.
0251 
0252 We'll just mention a couple of caveats the sub-interpreters support in pybind11:
0253 
0254  1. Sub-interpreters will not receive independent copies of embedded modules.
0255     Instead, these are shared and modifications in one interpreter may be
0256     reflected in another.
0257 
0258  2. Managing multiple threads, multiple interpreters and the GIL can be
0259     challenging and there are several caveats here, even within the pure
0260     CPython API (please refer to the Python docs for details). As for
0261     pybind11, keep in mind that ``gil_scoped_release`` and ``gil_scoped_acquire``
0262     do not take sub-interpreters into account.