PyO3 Python 解释器的 Rust 绑定开源项目

我要开发同款
匿名用户2021年01月15日
60阅读
开发技术Rust
所属分类Python开发工具、开发工具
授权协议Apache-2.0

作品详情

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

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

用法:

PyO3支持Python2.7和Python3.6及更高版本,Rust最低版本要求则是1.45.0。

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

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

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

sudoaptinstallpython3-devpython-dev在Python使用Rust:PyO3可用于生成本地Python模块。

Cargo.toml

[package]name="string-sum"version="0.1.0"edition="2018"[lib]name="string_sum"#"cdylib"isnecessarytoproduceasharedlibraryforPythontoimportfrom.##DownstreamRustcode(includingcodein`bin/`,`examples/`,and`tests/`)willnotbeable#to`usestring_sum;`unlessthe"rlib"or"lib"cratetypeisalsoincluded,e.g.:#crate-type=["cdylib","rlib"]crate-type=["cdylib"][dependencies.pyo3]version="0.13.1"features=["extension-module"]

src/lib.rs

usepyo3::prelude::*;usepyo3::wrap_pyfunction;///Formatsthesumoftwonumbersasstring.#[pyfunction]fnsum_as_string(a:usize,b:usize)->PyResult<String>{Ok((a+b).to_string())}///APythonmoduleimplementedinRust.#[pymodule]fnstring_sum(py:Python,m:&PyModule)->PyResult<()>{m.add_function(wrap_pyfunction!(sum_as_string,m)?)?;Ok(())}

在Windows和Linux上,可以使用命令cargobuild--release正常构建。在macOS上,则需要设置其他链接器参数。一种选择是使用cargorustc--release---Clink-arg=-undefined-Clink-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",]

在开发时,

https://unsplash.com/collections/97745155/https://unsplash.com/collections/55327332/https://unsplash.com/collections/18738157/https://unsplash.com/collections/83253510/https://unsplash.com/collections/85028995/https://unsplash.com/collections/73694405/https://unsplash.com/collections/73980211/

可以符号链接或复制(符号链接symlink,又称软连接)并重新命名目标文件夹的共享库;在macOS中,将libstring_sum.dylib重命名为string_sum.so,在Windows上将libstring_sum.dll重命名为string_sum.pyd以及在Linux上将libstring_sum.so重命名为string_sum.so。然后在同一文件夹中打开一个Pythonshell,就能够进行importstring_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的值和当前用户名:

usepyo3::prelude::*;usepyo3::types::IntoPyDict;fnmain()->Result<(),()>{Python::with_gil(|py|{main_(py).map_err(|e|{//Wecan'tdisplayPythonexceptionsviastd::fmt::Display,//soprinttheerrorheremanually.e.print_and_set_sys_last_vars(py);})})}fnmain_(py:Python)->PyResult<()>{letsys=py.import("sys")?;letversion:String=sys.get("version")?.extract()?;letlocals=[("os",py.import("os")?)].into_py_dict(py);letcode="os.getenv('USER')oros.getenv('USERNAME')or'Unknown'";letuser:String=py.eval(code,None,Some(&locals))?.extract()?;println!("Hello{},I'mPython{}",user,version);Ok(())}

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

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论