How to Call Python from Rust for Data Science (PyO3)

Use the PyO3 crate to initialize the Python interpreter and execute Python code directly within a Rust application.

Use the pyo3 crate to embed the Python interpreter and call Python functions directly from Rust. Add pyo3 to your Cargo.toml and initialize the interpreter in your main function before calling any Python code.

use pyo3::prelude::*;

fn main() -> PyResult<()> {
    Python::with_gil(|py| {
        let locals = pyo3::types::PyDict::new(py);
        py.run("import math", None, Some(locals))?;
        let result = py.eval("math.sqrt(2)", None, Some(locals))?;
        println!("Result: {}", result.extract::<f64>()?);
        Ok(())
    })
}
[dependencies]
pyo3 = { version = "0.20", features = ["auto-initialize"] }