zl程序教程

您现在的位置是:首页 >  Python

当前栏目

实战经验分享:使用 PyO3 来构建你的 Python 模块

2023-02-26 10:17:10 时间

版本规定如下:

Python 3.6+
Rust 1.41+
接下来我们通过一个小的 demo 了解一下从 PyO3 编译模块到 Python 中正常使用的整个流程。
cargo new –lib string-sum
创建项目

(福利推荐:阿里云、腾讯云、华为云服务器最新限时优惠活动,云服务器1核2G仅88元/年、2核4G仅698元/3年,点击这里立即抢购>>>

# lib.rs [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.14.1" features = ["extension-module"] // 扩展模块,像其他的还有auto-initialize
// src/lib.rs use std::usize;  use  pyo3::prelude::*;  // like this // def sum_as_string(a:str, b:str) -> str: //      return a+b #[pyfunction] fn sum_as_string(a: usize, b: usize) -> PyResult<String>{     Ok((a+b).to_string()) }  // Mount method to module  #[pymodule] fn string_sum(py: Python, m: &PyModule) -> PyResult<()>{     m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;     Ok(()) }

编译与使用
编译完成之后,我们会在 target 文件夹下面发现一个 wheel 文件。文件名组合为 “模块名 + 当前 Python 版本+当前系统型号”,比如:string_sum-0.1.0-cp39-cp39-macosx_10_7_x86_64.whl

pip3 install ./target/wheel/string_sum-0.1.0-cp39-cp39-macosx_10_7_x86_64.whl

创建 python 文件:

# example.py from string_sum import sum_as_string print(sum_as_string(1,2)) # echo 3

编译工具的选择和使用

官方提供了两种编译工具的选择:

rust 写的 maturin
传统的setup.py的方式
使用 maturin 编译

# 安装  pip3 install maturin # 编译 maturin build # maturin publish 发布 # 虚拟环境中使用 会自动去寻找/target/wheel/ 下的 *.wheel文件然后安装 virtualenv venv source ./venv/bin/activate maturin develop

使用 setup.py 编译

安装

pip3 install setuptools-rust

编写 setup.py 文件:

# setup.py   from setuptools import setup from setuptools_rust import Binding, RustExtension  setup(     # 包名称     name="string_sum",      # 包版本      version="0.1",     # rust扩展 其中"string_sum.string_sum"中     # 第一个string_sum 指的是当前的包     # 第二个指的是     # #[pymodule]     # fn string_sum(py: Python, m: &PyModule) -> PyResult<()>{     #     m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;     #     Ok(())     # }     # 中的string_sum     rust_extensions=[         RustExtension(             "string_sum.string_sum",              binding=Binding.PyO3,             debug=False             )     ],     # 需要创建一个文件夹 string_sum     packages=["string_sum"],     # rust extensions are not zip safe, just like C-extensions.     zip_safe=False,     # 标注     classifiers=[         "License :: OSI Approved :: MIT License",         "Development Status :: 3 - Alpha",         "Intended Audience :: Developers",         "Programming Language :: Python",         "Programming Language :: Rust",         "Operating System :: POSIX",         "Operating System :: MacOS :: MacOS X",     ],     include_package_data=True )
# 打包 mkdir string_sum touch string_sum/__init__.py virtualenv venv && source venv/bin/activate pip setup.py build && pip setup.py install && pip setup.py develop

docker 中的应用

同样的,如果创建的 App 本身是在 docker 内部运行的。那么第一步我们需要安装 rust 的环境 dockerfile。具体如下:

#!/bin/bash curl https://sh.rustup.rs -sSf | bash -s -- -y source $HOME/.cargo/env rustc --version python setup.py install  # ddockerfile  FROM python:3.7 WORKDIR /app ADD . /app RUN pip install --upgrade pip      && pip install -r requirements.txt RUN ./init.sh CMD [python, xx.py]  # requirements.txt semantic-version==2.8.5 setuptools-rust==0.12.1 toml==0.10.2  # rust国内镜像源 config # /root/.cargo/config [source.crates-io] registry = "https://github.com/rust-lang/crates.io-index" replace-with = 'ustc' [source.ustc] registry = "git://mirrors.ustc.edu.cn/crates.io-index" [term] verbose = true color = 'auto'

具体目录如下:

-rw-r--r-- Cargo.lock -rw-r--r-- Cargo.toml -rw-r--r-- config           # 配置文件 -rw-r--r-- Dockerfile -rwxrwxrwx init.sh          # 初始化rust环境脚本 -rw-r--r-- requirements.txt -rw-r--r-- setup.py         # 打包脚本 drwxr-xr-x src              # rust项目 drwxr-xr-x string_sum  -rw-r--r-- xx.py            # 可行性测试文件

如果你想开发小程序或者APP软件的话,可以通过专业开发公司,来帮助你实现开发需求:厦门在乎科技-专注厦门小程序开发公司、APP开发、网站开发、H5小游戏开发

实战经验分享:使用 PyO3 来构建你的 Python 模块


本站部分内容转载自网络,版权属于原作者所有,如有异议请联系QQ153890879修改或删除,谢谢!
转载请注明原文链接:实战经验分享:使用 PyO3 来构建你的 Python 模块

你还在原价购买阿里云、腾讯云、华为云、天翼云产品?那就亏大啦!现在申请成为四大品牌云厂商VIP用户,可以3折优惠价购买云服务器等云产品,并且可享四大云服务商产品终身VIP优惠价,还等什么?赶紧点击下面对应链接免费申请VIP客户吧:

1、点击这里立即申请成为腾讯云VIP客户

2、点击这里立即注册成为天翼云VIP客户

3、点击这里立即申请成为华为云VIP客户

4、点击这里立享阿里云产品终身VIP优惠价

喜欢 (0)
[[email protected]]
分享 (0)