Calling Python in Rust code
These APIs work from Rust whenever you have a Python
object handy, whether
PyO3 is built for an extension module or not.
Want to run just an expression? Then use eval
.
Python::eval
is
a method to execute a Python expression
and return the evaluated value as a &PyAny
object.
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() -> Result<(), ()> {
let gil = Python::acquire_gil();
let py = gil.python();
let result = py.eval("[i * 10 for i in range(5)]", None, None).map_err(|e| {
e.print_and_set_sys_last_vars(py);
})?;
let res: Vec<i64> = result.extract().unwrap();
assert_eq!(res, vec![0, 10, 20, 30, 40]);
Ok(())
}
Want to run statements? Then use run
.
Python::run
is a method to execute one or more
Python statements.
This method returns nothing (like any Python statement), but you can get
access to manipulated objects via the locals
dict.
You can also use the py_run!
macro, which is a shorthand for Python::run
.
Since py_run!
panics on exceptions, we recommend you use this macro only for
quickly testing your Python extensions.
You have a Python file or Python function? Then use PyModule
.
PyModule also can execute Python code by calling its methods.