Function pyo3::with_embedded_python_interpreter[][src]

pub unsafe fn with_embedded_python_interpreter<F, R>(f: F) -> R where
    F: for<'p> FnOnce(Python<'p>) -> R, 

Executes the provided closure with an embedded Python interpreter.

This function intializes 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.)


This function is only available when linking against Python distributions that contain a shared library.

This function is not available on PyPy.


  • If the Python interpreter is already initalized before calling this function.


  • 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.


use pyo3::prelude::*;

fn main() {
    unsafe {
        pyo3::with_embedded_python_interpreter(|py| {
  "print('Hello World')", None, None)