pub unsafe fn with_embedded_python_interpreter<F, R>(f: F) -> R
Available on neither
PyPy
nor GraalPy
.Expand description
Executes the provided closure with an embedded Python interpreter.
This function initializes the Python interpreter, executes the provided closure, and then finalizes the Python interpreter.
After execution all Python resources are cleaned up, and no further Python APIs can be called. Because many Python modules implemented in C do not support multiple Python interpreters in a single process, it is not safe to call this function more than once. (Many such modules will not initialize correctly on the second run.)
§Panics
- If the Python interpreter is already initialized before calling this function.
§Safety
- This function should only ever be called once per process (usually as part of the
main
function). It is also not thread-safe. - No Python APIs can be used after this function has finished executing.
- The return value of the closure must not contain any Python value, including
PyResult
.
§Examples
unsafe {
pyo3::with_embedded_python_interpreter(|py| {
if let Err(e) = py.run(pyo3::ffi::c_str!("print('Hello World')"), None, None) {
// We must make sure to not return a `PyErr`!
e.print(py);
}
});
}