PyO3是Pytho的Rust绑定,可以用Rust语言对Pytho加速。这包括用 Rust语言运行 Pytho代码并与之交互,以及直接编写原生 Pytho模块。
PyO3一开始只是作为 rust-cpytho 的分支出现,后来由于rust-cpytho缺乏维护,PyO3开始在Rust社区流行,随着时间推移PyO3与rust-cpytho有了根本的差异。由于导出包使用Rust语言开发,以及Rust语言速度快且内存利用率极高,因此在运行效率及性能上优于同等Pytho实现模块。
用法:PyO3支持Pytho2.7和Pytho3.6及更高版本,Rust最低版本要求则是1.45.0。
对于使用Pytho3.6的用户而言,也可以使用PyPy进行构建(通过cpyext),PyPy版本要求为7.3及以上。详情可以参阅指南中的pypy部分。
安装完成之后,就可以在Rust中编写原生 Pytho模块,也可以在Rust二进制文件中使用Pytho。
在部分操作系统上,如Ubutu18.04,则需要依赖一些其他软件包所提供的环境,针对这些系统需要运行以下命令:
sudoaptistallpytho3-devpytho-dev在Pytho使用Rust:PyO3可用于生成本地Pytho模块。Cargo.toml
[package]ame="strig-sum"versio="0.1.0"editio="2018"[lib]ame="strig_sum"#"cdylib"isecessarytoproduceasharedlibraryforPythotoimportfrom.##DowstreamRustcode(icludigcodei`bi/`,`examples/`,ad`tests/`)willotbeable#to`usestrig_sum;`ulessthe"rlib"or"lib"cratetypeisalsoicluded,e.g.:#crate-type=["cdylib","rlib"]crate-type=["cdylib"][depedecies.pyo3]versio="0.13.1"features=["extesio-module"]src/lib.rs
usepyo3::prelude::*;usepyo3::wrap_pyfuctio;///Formatsthesumoftwoumbersasstrig.#[pyfuctio]fsum_as_strig(a:usize,b:usize)->PyResult<Strig>{Ok((a+b).to_strig())}///APythomoduleimplemetediRust.#[pymodule]fstrig_sum(py:Pytho,m:&PyModule)->PyResult<()>{m.add_fuctio(wrap_pyfuctio!(sum_as_strig,m)?)?;Ok(())}在Widows和Liux上,可以使用命令cargobuild--release正常构建。在macOS上,则需要设置其他链接器参数。一种选择是使用cargorustc--release---Clik-arg=-udefied-Clik-arg=dyamic_lookup进行编译,另一种方法是使用以下命令创建一个.cargo/cofig:
[target.x86_64-apple-darwi]rustflags=["-C","lik-arg=-udefied","-C","lik-arg=dyamic_lookup",][target.aarch64-apple-darwi]rustflags=["-C","lik-arg=-udefied","-C","lik-arg=dyamic_lookup",]在开发时,
https://usplash.com/collectios/97745155/https://usplash.com/collectios/55327332/https://usplash.com/collectios/18738157/https://usplash.com/collectios/83253510/https://usplash.com/collectios/85028995/https://usplash.com/collectios/73694405/https://usplash.com/collectios/73980211/
可以符号链接或复制(符号链接symlik,又称软连接)并重新命名目标文件夹的共享库;在macOS中,将libstrig_sum.dylib重命名为strig_sum.so,在Widows上将libstrig_sum.dll重命名为strig_sum.pyd以及在Liux上将libstrig_sum.so重命名为strig_sum.so。然后在同一文件夹中打开一个Pythoshell,就能够进行importstrig_sum操作。
可以使用 maturi 或 setuptools-rust 来构建、测试和发布你创建的Pytho模块。具体的setuptools-rust示范用例可以在 examples/word-cout中找到,而maturi则无需任何配置即可直接使用。在Rust使用Pytho:如果你想要用 Rust应用程序在内部创建一个Pytho解释器并使用它来运行Pytho代码,那么将pyo3按照如下方式添加进Cargo.toml:[depedecies.pyo3]versio="0.13.1"features=["auto-iitialize"]示例程序显示了sys.versio的值和当前用户名:
usepyo3::prelude::*;usepyo3::types::ItoPyDict;fmai()->Result<(),()>{Pytho::with_gil(|py|{mai_(py).map_err(|e|{//Weca'tdisplayPythoexceptiosviastd::fmt::Display,//soprittheerrorheremaually.e.prit_ad_set_sys_last_vars(py);})})}fmai_(py:Pytho)->PyResult<()>{letsys=py.import("sys")?;letversio:Strig=sys.get("versio")?.extract()?;letlocals=[("os",py.import("os")?)].ito_py_dict(py);letcode="os.getev('USER')oros.getev('USERNAME')or'Ukow'";letuser:Strig=py.eval(code,Noe,Some(&locals))?.extract()?;pritl!("Hello{},I'mPytho{}",user,versio);Ok(())}更多关于PyO3的示例,可以查看官方指南。










评论