Skip to content

Instantly share code, notes, and snippets.

@jmcph4
Last active September 6, 2024 05:14
Show Gist options
  • Select an option

  • Save jmcph4/b8879dd5299d539ec13acbc17c481135 to your computer and use it in GitHub Desktop.

Select an option

Save jmcph4/b8879dd5299d539ec13acbc17c481135 to your computer and use it in GitHub Desktop.
PyO3 recipes
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() -> PyResult<()> {
Python::with_gil(|py| {
let locals = [("pd", py.import_bound("pandas")?)].into_py_dict_bound(py);
let code = "pd.DataFrame({})";
let res = py.eval_bound(code, None, Some(&locals))?;
println!("{res:?}");
Ok(())
})
}
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() -> PyResult<()> {
Python::with_gil(|py| {
let sys = py.import_bound("sys")?;
let version: String = sys.getattr("version")?.extract()?;
let locals = [("os", py.import_bound("os")?)].into_py_dict_bound(py);
let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;
println!("Hello {}, I'm Python {}", user, version);
Ok(())
})
}
use pyo3::prelude::*;
fn main() -> PyResult<()> {
Python::with_gil(|py| {
py.eval_bound("print('Hello, world!')", None, None)?;
Ok(())
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment