PyO3介绍
PyO3 可用于生成本机 Python 模块。最简单的方法就是 第一次是使用 maturin。 是构建和发布基于 Rust 的工具 具有最少配置的 Python 包
参考链接
https://docs.rs/pyo3-ffi/latest/pyo3_ffi/#using-python-from-rust
https://github.com/PyO3/pyo3
rust 版本 python版本
python调用rust代码
初始化项目例如 py_rust
新建一个空白项目,本机器必须装好rust和python
必须都是相同位数的版本不然后续会报错
> error: your Rust target architecture (64-bit) does not match your python interpreter (32-bit) 💥 maturin failed Caused by: Failed to build a native library through cargo Caused by: Cargo build finished with "exit code: 101": `"cargo" "rustc" "--features" "pyo3/extension-module" "--message-format" "json-render-diagnostics" "--manifest-path" "C:\\project\\rust\\py_rust\\Cargo.toml" "--lib"`
下面是命令行操作 主要是安装maturin:
maturin 介绍:
使用 pyo3、cffi 和 uniffi 绑定以及 Rust 二进制文件以最少的配置构建和发布 crate 作为 python 包
cd py_rust
python -m venv .env #python项目虚拟环境
cd .\.env\Scripts\
.\activate #激活虚拟环境
pip install maturin
安装 maturin
cd py_rust
maturin init
使用
执行命令构建rust的lib为python依赖
maturin develop
deactivate # 关闭虚拟环境
rust调用python代码
要将 Python 嵌入到 Rust 二进制文件中,您需要确保您的 Python 安装包含共享库
新建rust项目 如:rust_py
引入依赖
cd py_rust
python -m venv .env #python项目虚拟环境
cd .\.env\Scripts\
.\activate #激活虚拟环境
use pyo3::ffi::*;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() {
//例子1
let res1:Result<String,PyErr>=Python::with_gil(|py|{
let uuid_mod=py.import_bound("uuid")?;
let uuid_obj=uuid_mod.call_method1("uuid4",())?;
// 将 UUID 对象转换为字符串
let uuid_str:String = uuid_obj.call_method1("__str__",())?.extract()?;
// let uuid_str::String =uuid_obj.call_method1("_str_",())?.extract()?;
Ok(uuid_str)
});
match res1 {
Ok(res_uuid)=>{println!("{res_uuid}")}
Err(err)=>{println!("{err}")}
}
//例子2
let res2:Result<String,PyErr>=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 = stringify!("os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'");
let user: String = py.eval_bound(code, None, Some(&locals))?.extract()?;
Ok((format!("Hello {}, I'm Python {}", user, version)))
});
match res2 {
Ok(user)=>{println!("{user}")}
Err(err)=>{println!("{err}")}
}
}