embedding.rst 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. .. _embedding:
  2. Embedding the interpreter
  3. #########################
  4. While pybind11 is mainly focused on extending Python using C++, it's also
  5. possible to do the reverse: embed the Python interpreter into a C++ program.
  6. All of the other documentation pages still apply here, so refer to them for
  7. general pybind11 usage. This section will cover a few extra things required
  8. for embedding.
  9. Getting started
  10. ===============
  11. A basic executable with an embedded interpreter can be created with just a few
  12. lines of CMake and the ``pybind11::embed`` target, as shown below. For more
  13. information, see :doc:`/compiling`.
  14. .. code-block:: cmake
  15. cmake_minimum_required(VERSION 3.0)
  16. project(example)
  17. find_package(pybind11 REQUIRED) # or `add_subdirectory(pybind11)`
  18. add_executable(example main.cpp)
  19. target_link_libraries(example PRIVATE pybind11::embed)
  20. The essential structure of the ``main.cpp`` file looks like this:
  21. .. code-block:: cpp
  22. #include <pybind11/embed.h> // everything needed for embedding
  23. namespace py = pybind11;
  24. int main() {
  25. py::scoped_interpreter guard{}; // start the interpreter and keep it alive
  26. py::print("Hello, World!"); // use the Python API
  27. }
  28. The interpreter must be initialized before using any Python API, which includes
  29. all the functions and classes in pybind11. The RAII guard class `scoped_interpreter`
  30. takes care of the interpreter lifetime. After the guard is destroyed, the interpreter
  31. shuts down and clears its memory. No Python functions can be called after this.
  32. Executing Python code
  33. =====================
  34. There are a few different ways to run Python code. One option is to use `eval`,
  35. `exec` or `eval_file`, as explained in :ref:`eval`. Here is a quick example in
  36. the context of an executable with an embedded interpreter:
  37. .. code-block:: cpp
  38. #include <pybind11/embed.h>
  39. namespace py = pybind11;
  40. int main() {
  41. py::scoped_interpreter guard{};
  42. py::exec(R"(
  43. kwargs = dict(name="World", number=42)
  44. message = "Hello, {name}! The answer is {number}".format(**kwargs)
  45. print(message)
  46. )");
  47. }
  48. Alternatively, similar results can be achieved using pybind11's API (see
  49. :doc:`/advanced/pycpp/index` for more details).
  50. .. code-block:: cpp
  51. #include <pybind11/embed.h>
  52. namespace py = pybind11;
  53. using namespace py::literals;
  54. int main() {
  55. py::scoped_interpreter guard{};
  56. auto kwargs = py::dict("name"_a="World", "number"_a=42);
  57. auto message = "Hello, {name}! The answer is {number}"_s.format(**kwargs);
  58. py::print(message);
  59. }
  60. The two approaches can also be combined:
  61. .. code-block:: cpp
  62. #include <pybind11/embed.h>
  63. #include <iostream>
  64. namespace py = pybind11;
  65. using namespace py::literals;
  66. int main() {
  67. py::scoped_interpreter guard{};
  68. auto locals = py::dict("name"_a="World", "number"_a=42);
  69. py::exec(R"(
  70. message = "Hello, {name}! The answer is {number}".format(**locals())
  71. )", py::globals(), locals);
  72. auto message = locals["message"].cast<std::string>();
  73. std::cout << message;
  74. }
  75. Importing modules
  76. =================
  77. Python modules can be imported using `module::import()`:
  78. .. code-block:: cpp
  79. py::module sys = py::module::import("sys");
  80. py::print(sys.attr("path"));
  81. For convenience, the current working directory is included in ``sys.path`` when
  82. embedding the interpreter. This makes it easy to import local Python files:
  83. .. code-block:: python
  84. """calc.py located in the working directory"""
  85. def add(i, j):
  86. return i + j
  87. .. code-block:: cpp
  88. py::module calc = py::module::import("calc");
  89. py::object result = calc.attr("add")(1, 2);
  90. int n = result.cast<int>();
  91. assert(n == 3);
  92. Modules can be reloaded using `module::reload()` if the source is modified e.g.
  93. by an external process. This can be useful in scenarios where the application
  94. imports a user defined data processing script which needs to be updated after
  95. changes by the user. Note that this function does not reload modules recursively.
  96. .. _embedding_modules:
  97. Adding embedded modules
  98. =======================
  99. Embedded binary modules can be added using the `PYBIND11_EMBEDDED_MODULE` macro.
  100. Note that the definition must be placed at global scope. They can be imported
  101. like any other module.
  102. .. code-block:: cpp
  103. #include <pybind11/embed.h>
  104. namespace py = pybind11;
  105. PYBIND11_EMBEDDED_MODULE(fast_calc, m) {
  106. // `m` is a `py::module` which is used to bind functions and classes
  107. m.def("add", [](int i, int j) {
  108. return i + j;
  109. });
  110. }
  111. int main() {
  112. py::scoped_interpreter guard{};
  113. auto fast_calc = py::module::import("fast_calc");
  114. auto result = fast_calc.attr("add")(1, 2).cast<int>();
  115. assert(result == 3);
  116. }
  117. Unlike extension modules where only a single binary module can be created, on
  118. the embedded side an unlimited number of modules can be added using multiple
  119. `PYBIND11_EMBEDDED_MODULE` definitions (as long as they have unique names).
  120. These modules are added to Python's list of builtins, so they can also be
  121. imported in pure Python files loaded by the interpreter. Everything interacts
  122. naturally:
  123. .. code-block:: python
  124. """py_module.py located in the working directory"""
  125. import cpp_module
  126. a = cpp_module.a
  127. b = a + 1
  128. .. code-block:: cpp
  129. #include <pybind11/embed.h>
  130. namespace py = pybind11;
  131. PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
  132. m.attr("a") = 1;
  133. }
  134. int main() {
  135. py::scoped_interpreter guard{};
  136. auto py_module = py::module::import("py_module");
  137. auto locals = py::dict("fmt"_a="{} + {} = {}", **py_module.attr("__dict__"));
  138. assert(locals["a"].cast<int>() == 1);
  139. assert(locals["b"].cast<int>() == 2);
  140. py::exec(R"(
  141. c = a + b
  142. message = fmt.format(a, b, c)
  143. )", py::globals(), locals);
  144. assert(locals["c"].cast<int>() == 3);
  145. assert(locals["message"].cast<std::string>() == "1 + 2 = 3");
  146. }
  147. Interpreter lifetime
  148. ====================
  149. The Python interpreter shuts down when `scoped_interpreter` is destroyed. After
  150. this, creating a new instance will restart the interpreter. Alternatively, the
  151. `initialize_interpreter` / `finalize_interpreter` pair of functions can be used
  152. to directly set the state at any time.
  153. Modules created with pybind11 can be safely re-initialized after the interpreter
  154. has been restarted. However, this may not apply to third-party extension modules.
  155. The issue is that Python itself cannot completely unload extension modules and
  156. there are several caveats with regard to interpreter restarting. In short, not
  157. all memory may be freed, either due to Python reference cycles or user-created
  158. global data. All the details can be found in the CPython documentation.
  159. .. warning::
  160. Creating two concurrent `scoped_interpreter` guards is a fatal error. So is
  161. calling `initialize_interpreter` for a second time after the interpreter
  162. has already been initialized.
  163. Do not use the raw CPython API functions ``Py_Initialize`` and
  164. ``Py_Finalize`` as these do not properly handle the lifetime of
  165. pybind11's internal data.
  166. Sub-interpreter support
  167. =======================
  168. Creating multiple copies of `scoped_interpreter` is not possible because it
  169. represents the main Python interpreter. Sub-interpreters are something different
  170. and they do permit the existence of multiple interpreters. This is an advanced
  171. feature of the CPython API and should be handled with care. pybind11 does not
  172. currently offer a C++ interface for sub-interpreters, so refer to the CPython
  173. documentation for all the details regarding this feature.
  174. We'll just mention a couple of caveats the sub-interpreters support in pybind11:
  175. 1. Sub-interpreters will not receive independent copies of embedded modules.
  176. Instead, these are shared and modifications in one interpreter may be
  177. reflected in another.
  178. 2. Managing multiple threads, multiple interpreters and the GIL can be
  179. challenging and there are several caveats here, even within the pure
  180. CPython API (please refer to the Python docs for details). As for
  181. pybind11, keep in mind that `gil_scoped_release` and `gil_scoped_acquire`
  182. do not take sub-interpreters into account.