From f6195de0c7d106bedd2f2d83745026ef548cf22b Mon Sep 17 00:00:00 2001 From: Roland Schwan Date: Sat, 2 Mar 2024 10:57:34 +0100 Subject: [PATCH] cleanup python interpreter at exit --- include/piqp/utils/io_utils.hpp | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/include/piqp/utils/io_utils.hpp b/include/piqp/utils/io_utils.hpp index 262b456..7f81f4f 100644 --- a/include/piqp/utils/io_utils.hpp +++ b/include/piqp/utils/io_utils.hpp @@ -18,7 +18,15 @@ namespace piqp { -bool init_interpreter = false; +static bool py_interpreter_initialized = false; +static void cleanup_py_interpreter() +{ + namespace py = pybind11; + if (py_interpreter_initialized) { + py::finalize_interpreter(); + py_interpreter_initialized = false; + } +} template void save_dense_model(const dense::Model& model, const std::string& path) @@ -26,9 +34,10 @@ void save_dense_model(const dense::Model& model, const std::string& path) namespace py = pybind11; using namespace pybind11::literals; - if (!init_interpreter) { + if (!py_interpreter_initialized) { py::initialize_interpreter(); - init_interpreter = true; + py_interpreter_initialized = true; + std::atexit(cleanup_py_interpreter); } py::str py_path = path; @@ -53,9 +62,10 @@ void save_sparse_model(const sparse::Model& model, const std::string& path namespace py = pybind11; using namespace pybind11::literals; - if (!init_interpreter) { + if (!py_interpreter_initialized) { py::initialize_interpreter(); - init_interpreter = true; + py_interpreter_initialized = true; + std::atexit(cleanup_py_interpreter); } py::str py_path = path; @@ -80,9 +90,10 @@ dense::Model load_dense_model(const std::string& path) namespace py = pybind11; using namespace pybind11::literals; - if (!init_interpreter) { + if (!py_interpreter_initialized) { py::initialize_interpreter(); - init_interpreter = true; + py_interpreter_initialized = true; + std::atexit(cleanup_py_interpreter); } py::object spio = py::module_::import("scipy.io"); @@ -107,9 +118,10 @@ sparse::Model load_sparse_model(const std::string& path) namespace py = pybind11; using namespace pybind11::literals; - if (!init_interpreter) { + if (!py_interpreter_initialized) { py::initialize_interpreter(); - init_interpreter = true; + py_interpreter_initialized = true; + std::atexit(cleanup_py_interpreter); } py::object spio = py::module_::import("scipy.io");