pub fn py_exec<F, R>(closure: F) -> RExpand description
Runs a closure that follows the signature |py: RUMPython| -> R {}.
Remember, the type of the py token needs to be explicitly added or there will be a type
inference error from Rust about lifetimes when in fact the closure has no lifetime issues.
See example below.
§Examples
§Running A Function With Arguments and Result
use std::fs::write;
use pyo3::Python;
use uuid::Uuid;
use crate::rumtk_core::core::RUMResult;
use crate::rumtk_core::scripting::python_utils::{py_extract_any, py_new_args, py_push_arg, py_exec, py_exec_module, py_load, RUMPython};
use crate::rumtk_core::scripting::python_utils::{RUMPyModule};
fn test_module_exec() -> f64 {
let module_fname = format!("{}_module.py", Uuid::new_v4());
let module_contents = "def test(a,b):\n\treturn a+b";
write(&module_fname, module_contents).expect("Failed to write file!");
let closure = |py: RUMPython| -> RUMResult<f64> {
let a = 5;
let b = 5.0;
let mut args = py_new_args(py);
py_push_arg(py, &mut args, &a);
py_push_arg(py, &mut args, &b);
let pymod: RUMPyModule = py_load(py, &module_fname).expect("Failure to load module!");
let result = py_exec_module(py, &pymod, "test", &args).unwrap();
let val: f64 = py_extract_any(py, &result).unwrap();
Ok(val)
};
let result = py_exec(closure);
std::fs::remove_file(&module_fname).unwrap();
result.unwrap()
}
let result = test_module_exec();
assert_eq!(10.0, result, "Bad value returned from Python snippet!")