如何使用PyO3等库在Python中运行Rust代码,rust中调用python代码

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}")}
    }
}



在这里插入图片描述

可以通过使用`pyo3`库来将`Python`类方法导出到`Rust`,然后在`Rust`调用这些方法。以下是一个例子: ```python # example.py class MyClass: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") ``` ```rust // main.rs use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[pyclass] struct MyClass { name: String, } #[pymethods] impl MyClass { #[new] fn new(name: String) -> Self { Self { name } } fn greet(&self) -> PyResult<()> { Python::with_gil(|py| { let gil = pyo3::Python::acquire_gil(); let py = gil.python(); let locals = [("self", pyo3::PyObject::from(self))].into_py_dict(py); py.run("self.greet()", None, Some(&locals))?; Ok(()) }) } } #[pyfunction] fn create_my_class(name: String) -> PyResult<MyClass> { Ok(MyClass::new(name)) } #[pymodule] fn example(_py: Python, m: &PyModule) -> PyResult<()> { m.add_class::<MyClass>()?; m.add_wrapped(wrap_pyfunction!(create_my_class))?; Ok(()) } fn main() -> PyResult<()> { Python::with_gil(|py| { let example_module = PyModule::new(py, "example")?; example_module.add_class::<MyClass>()?; example_module.add_wrapped(wrap_pyfunction!(create_my_class))?; let locals = [("example", example_module)].into_py_dict(py); py.run("import example", None, Some(&locals))?; let my_class = example_module .call("create_my_class", ("World",), None)? .extract::<MyClass>()?; my_class.greet()?; Ok(()) }) } ``` 这个例子,我们使用`pyo3`库将`Python`类`MyClass`导出到`Rust`。在`Rust`代码,我们可以通过调用`MyClass`的`greet`方法来执行`Python`类的`greet`方法。我们还编写了一个`Rust`函数`create_my_class`,用于创建`MyClass`实例并将其返回到`Python`。最后,我们在`Rust`调用`Python`代码来创建`MyClass`实例,然后调用`greet`方法来打印出“Hello, World!”的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值