\rst Scope guard version of `initialize_interpreter` and `finalize_interpreter`. This a move-only guard and only a single instance can exist. See `initialize_interpreter` for a discussion of its constructor arguments. .. code-block:: cpp #include int main() { py::scoped_interpreter guard{}; py::print(Hello, World!);
| 285 | } // <-- interpreter shutdown |
| 286 | \endrst */ |
| 287 | class scoped_interpreter { |
| 288 | public: |
| 289 | explicit scoped_interpreter(bool init_signal_handlers = true, |
| 290 | int argc = 0, |
| 291 | const char *const *argv = nullptr, |
| 292 | bool add_program_dir_to_path = true) { |
| 293 | initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path); |
| 294 | } |
| 295 | |
| 296 | #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX |
| 297 | explicit scoped_interpreter(PyConfig *config, |
| 298 | int argc = 0, |
| 299 | const char *const *argv = nullptr, |
| 300 | bool add_program_dir_to_path = true) { |
| 301 | initialize_interpreter(config, argc, argv, add_program_dir_to_path); |
| 302 | } |
| 303 | #endif |
| 304 | |
| 305 | scoped_interpreter(const scoped_interpreter &) = delete; |
| 306 | scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; } |
| 307 | scoped_interpreter &operator=(const scoped_interpreter &) = delete; |
| 308 | scoped_interpreter &operator=(scoped_interpreter &&) = delete; |
| 309 | |
| 310 | ~scoped_interpreter() { |
| 311 | if (is_valid) { |
| 312 | finalize_interpreter(); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | private: |
| 317 | bool is_valid = true; |
| 318 | }; |
| 319 | |
| 320 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) |