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
41#include <pybind11/embed.h>
42#include <pybind11/eval.h>
43#include <pybind11/pybind11.h>
44
67
71 pybind11::dict locals;
72
76 PyScriptHandle() { std::make_unique<pybind11::dict>(); }
77
83 pybind11::dict &data() { return locals; }
84
92 template<class T>
93 inline void register_array(std::string name, std::vector<T> &arr) {
94 data()[name.c_str()] = arr;
95 }
96
104 template<class T>
105 inline void register_value(std::string name, T val) {
106 data()[name.c_str()] = val;
107 }
108
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};
Class allowing use of python scripts within a test case.
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.