github.com/kaydxh/golang@v0.0.131/pkg/gocv/cgo/third_path/pybind11/docs/advanced/embedding.rst (about)

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