Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
PyScriptHandle.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
38
41#include <pybind11/embed.h>
42#include <pybind11/eval.h>
43#include <pybind11/pybind11.h>
44
62 * plt.show()
63 * )");
64 * \endcode
65 */
66struct PyScriptHandle {
71 pybind11::dict locals;
76 PyScriptHandle() { std::make_unique<pybind11::dict>(); }
77
83 pybind11::dict &data() { return locals; }
84
89 * @param name name of the python variable
90 * @param arr the array to pass
91 */
92 template<class T>
93 inline void register_array(std::string name, std::vector<T> &arr) {
94 data()[name.c_str()] = arr;
95 }
96
101 * @param name name of the python variable
102 * @param val the value to pass
103 */
104 template<class T>
105 inline void register_value(std::string name, T val) {
106 data()[name.c_str()] = val;
107 }
108
115 * @return true the script executed successfully
116 * @return false the script executed with an error
117 */
118 template<size_t N>
119 inline bool exec(const char (&expr)[N], pybind11::object &&global = pybind11::globals()) {
120 try {
121 py::exec(expr, std::forward<pybind11::object>(global), locals);
122 } catch (const std::exception &e) {
123 logger::warn_ln("PyScriptHandle", "the script throwed an error :", e.what());
124 return false;
125 }
126 return true;
127 }
128};
void warn_ln(std::string module_name, Types... var2)
Prints a log message with multiple arguments followed by a newline.
Definition logs.hpp:133
bool exec(const char(&expr)[N], pybind11::object &&global=pybind11::globals())
execute the given script
pybind11::dict & data()
return reference to the locals
void register_value(std::string name, T val)
register a value in a local py variable
void register_array(std::string name, std::vector< T > &arr)
register an array in a local py variable
pybind11::dict locals
local python variables
PyScriptHandle()
Construct PyScriptHandle and create an instance of PyScriptHandle::locals.