rust edition python3_PyO3首页、文档和下载 - Python 解释器的 Rust 绑定

PyO3是Rust对Python的绑定库,允许在Rust中运行和交互Python代码,创建高效原生Python模块。支持Python 2.7和3.6+,Rust最低要求1.45.0。通过PyO3,开发者可以在Rust中编写Python模块,或在Rust应用内部运行Python解释器。安装后,可以使用cargo构建,而在某些操作系统上可能需要额外的软件包。PyO3还支持使用maturin或setuptools-rust构建、测试和发布Python模块。
摘要由CSDN通过智能技术生成

PyO3 是 Python 的 Rust 绑定,可以用 Rust 语言对 Python 加速。这包括用 Rust 语言运行 Python 代码并与之交互,以及直接编写原生 Python 模块。

PyO3 一开始只是作为 rust-cpython 的分支出现, 后来由于 rust-cpython 缺乏维护, PyO3 开始在 Rust 社区流行, 随着时间推移 PyO3 与 rust-cpython 有了根本的差异。由于导出包使用 Rust 语言开发,以及 Rust 语言速度快且内存利用率极高,因此在运行效率及性能上优于同等 Python 实现模块。

用法:

PyO3 支持 Python 2.7 和 Python 3.6 及更高版本,Rust 最低版本要求则是 1.45.0。

对于使用 Python 3.6 的用户而言,也可以使用 PyPy 进行构建(通过 cpyext),PyPy 版本要求为 7.3 及以上。详情可以参阅指南中的 pypy 部分。

安装完成之后,就可以在 Rust 中编写原生 Python 模块,也可以在 Rust 二进制文件中使用 Python。

在部分操作系统上,如 Ubuntu 18.04,则需要依赖一些其他软件包所提供的环境,针对这些系统需要运行以下命令:

sudo apt install python3-dev python-dev

在 Python 使用 Rust:

PyO3 可用于生成本地 Python 模块。

Cargo.toml

[package]

name = "string-sum"

version = "0.1.0"

edition = "2018"

[lib]

name = "string_sum"

# "cdylib" is necessary to produce a shared library for Python to import from.

#

# Downstream Rust code (including code in `bin/`, `examples/`, and `tests/`) will not be able

# to `use string_sum;` unless the "rlib" or "lib" crate type is also included, e.g.:

# crate-type = ["cdylib", "rlib"]

crate-type = ["cdylib"]

[dependencies.pyo3]

version = "0.13.1"

features = ["extension-module"]

src/lib.rs

use pyo3::prelude::*;

use pyo3::wrap_pyfunction;

/// Formats the sum of two numbers as string.

#[pyfunction]

fn sum_as_string(a: usize, b: usize) -> PyResult {

Ok((a + b).to_string())

}

/// A Python module implemented in Rust.

#[pymodule]

fn string_sum(py: Python, m: &PyModule) -> PyResult {

m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;

Ok(())

}

在 Windows 和 Linux 上,可以使用命令cargo build --release正常构建。在 macOS 上,则需要设置其他链接器参数。一种选择是使用cargo rustc --release -- -C link-arg=-undefined -C link-arg=dynamic_lookup进行编译,另一种方法是使用以下命令创建一个.cargo/config:

[target.x86_64-apple-darwin]

rustflags = [

"-C", "link-arg=-undefined",

"-C", "link-arg=dynamic_lookup",

]

[target.aarch64-apple-darwin]

rustflags = [

"-C", "link-arg=-undefined",

"-C", "link-arg=dynamic_lookup",

]

在开发时,可以符号链接或复制(符号链接 symlink,又称软连接)并重新命名目标文件夹的共享库;在 macOS 中,将libstring_sum.dylib重命名为string_sum.so,在 Windows 上将libstring_sum.dll重命名为string_sum.pyd以及在 Linux 上将libstring_sum.so重命名为string_sum.so。然后在同一文件夹中打开一个 Python shell,就能够进行import string_sum操作。

可以使用 maturin 或 setuptools-rust 来构建、测试和发布你创建的 Python 模块。具体的 setuptools-rust 示范用例可以在 examples / word-count中找到,而 maturin 则无需任何配置即可直接使用。

在 Rust 使用 Python:

如果你想要用 Rust 应用程序在内部创建一个 Python 解释器并使用它来运行Python代码,那么将pyo3按照如下方式添加进Cargo.toml:

[dependencies.pyo3]

version = "0.13.1"

features = ["auto-initialize"]

示例程序显示了sys.version的值和当前用户名:

use pyo3::prelude::*;

use pyo3::types::IntoPyDict;

fn main() -> Result {

Python::with_gil(|py| {

main_(py).map_err(|e| {

// We can't display Python exceptions via std::fmt::Display,

// so print the error here manually.

e.print_and_set_sys_last_vars(py);

})

})

}

fn main_(py: Python) -> PyResult {

let sys = py.import("sys")?;

let version: String = sys.get("version")?.extract()?;

let locals = [("os", py.import("os")?)].into_py_dict(py);

let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";

let user: String = py.eval(code, None, Some(&locals))?.extract()?;

println!("Hello {}, I'm Python {}", user, version);

Ok(())

}

更多关于 PyO3 的示例,可以查看官方指南。

可以通过使用`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、付费专栏及课程。

余额充值