PyO3 使用者指南
歡迎閱讀 PyO3 使用者指南!本書是 PyO3 API 文件 的輔助說明,包含範例與文件,詳細解釋 PyO3 的各種使用情境。
本指南內容的大致順序如下:
- 開始使用
- 封裝 Rust 程式碼供 Python 使用
- 如何從 Rust 使用 Python 程式碼
- 其餘深入進階概念的主題
請從左側章節選擇主題,或繼續往下閱讀 PyO3 的 README。
PyO3
提供 Rust 對 Python 的綁定,包含建立原生 Python 擴充模組的工具;也支援在 Rust 二進位程式中執行並與 Python 程式碼互動。
使用方式
需要 Rust 1.83 或更高版本。
PyO3 支援以下 Python 散布版:
- CPython 3.7 或更高版本
- PyPy 7.3(Python 3.11+)
- GraalPy 25.0 或更高版本(Python 3.12+)
你可以使用 PyO3 以 Rust 撰寫原生 Python 模組,或在 Rust 二進位程式中嵌入 Python。以下各節將依序說明。
從 Python 使用 Rust
PyO3 可用來產生原生 Python 模組。第一次嘗試最簡單的方法是使用 maturin。maturin 是用來以最少設定建置並發布以 Rust 為基礎的 Python 軟體包的工具。以下步驟會安裝 maturin、用它產生並建置新的 Python 軟體包,接著啟動 Python 匯入並執行軟體包中的函式。
首先,依照以下命令建立一個包含 Python virtualenv 的新目錄,並使用 Python 軟體包管理工具 pip 將 maturin 安裝到該 virtualenv:
#(將 string_sum 替換為想要的軟體包名稱)
$ mkdir string_sum
$ cd string_sum
$ python -m venv .env
$ source .env/bin/activate
$ pip install maturin
仍在這個 string_sum 目錄中時,執行 maturin init。這會產生新的軟體包來源碼。當詢問要使用哪種綁定時,選擇 pyo3 綁定:
$ maturin init
✔ 🤷 What kind of bindings to use? · pyo3
✨ Done! New project created string_sum
此命令產生的最重要檔案是 Cargo.toml 與 lib.rs,大致如下:
Cargo.toml
[package]
name = "string_sum"
version = "0.1.0"
edition = "2021"
[lib]
# The name of the native library. This is the name which will be used in Python to import the
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
# `#[pymodule]` in `src/lib.rs`.
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 = "0.28.2"
src/lib.rs
/// 以 Rust 實作的 Python 模組。此模組名稱必須與 `Cargo.toml` 中的
/// `lib.name` 設定一致,否則 Python 將無法
/// 匯入此模組。
#[pyo3::pymodule]
mod string_sum {
use pyo3::prelude::*;
/// 將兩個數字的總和格式化為字串。
#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
Ok((a + b).to_string())
}
}
最後,執行 maturin develop。這會建置軟體包並安裝到先前建立並啟用的 Python virtualenv。接著即可在 python 中使用該軟體包:
$ maturin develop
# maturin 執行編譯時會輸出大量進度訊息...
$ python
>>> import string_sum
>>> string_sum.sum_as_string(5, 20)
'25'
要修改軟體包時,只需編輯 Rust 來源碼,然後重新執行 maturin develop 以重新編譯。
若要一次複製貼上完成全部步驟,請使用下列 bash 腳本(將第一個命令中的 string_sum 替換為想要的軟體包名稱):
mkdir string_sum && cd "$_"
python -m venv .env
source .env/bin/activate
pip install maturin
maturin init --bindings pyo3
maturin develop
如果你想要執行 cargo test 或在 Cargo workspace 中使用此專案,但遇到連結器問題,可參考 FAQ 的替代做法。
除了 maturin 之外,也可以使用 setuptools-rust 或手動建置。兩者都比 maturin 更有彈性,但起步時需要更多設定。
從 Rust 使用 Python
若要在 Rust 二進位程式中嵌入 Python,你需要確保 Python 安裝包含共享程式庫。以下步驟示範如何(在 Ubuntu 上)完成此設定,並提供一段執行嵌入式 Python 直譯器的範例程式碼。
在 Ubuntu 上安裝 Python 共享程式庫:
sudo apt install python3-dev
在基於 RPM 的散佈版(如 Fedora、Red Hat、SuSE)上,請安裝 python3-devel 軟體包以取得 Python 共享程式庫。
使用 cargo new 建立新專案,並在 Cargo.toml 中加入 pyo3:
[dependencies.pyo3]
version = "0.28.2"
# Enabling this cargo feature will cause PyO3 to start a Python interpreter on first call to `Python::attach`
features = ["auto-initialize"]
顯示 sys.version 與目前使用者名稱的範例程式:
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
fn main() -> PyResult<()> {
Python::attach(|py| {
let sys = py.import("sys")?;
let version: String = sys.getattr("version")?.extract()?;
let locals = [("os", py.import("os")?)].into_py_dict(py)?;
let code = c"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(())
})
}
指南中有專章提供大量相關範例。
工具與程式庫
- maturin 使用 pyo3、rust-cpython 或 cffi 綁定建置並發布 crate,並將 Rust 二進位程式打包為 Python 軟體包
- setuptools-rust 為 Rust 提供支援的 Setuptools 外掛。
- pyo3-built 透過簡單的巨集將
builtcrate 取得的中繼資料以PyDict形式暴露 - rust-numpy NumPy C-API 的 Rust 綁定
- dict-derive Derive FromPyObject 以自動將 Python dict 轉為 Rust struct
- pyo3-log 將 Rust 連接到 Python 日誌系統的橋接
- pythonize 用於將 Rust 物件轉成相容 JSON 的 Python 物件的 Serde 序列化工具
- pyo3-async-runtimes 與 Python 的 Asyncio 程式庫與 Rust 的 async runtime 互通的工具
- rustimport 可在 Python 直接匯入 Rust 檔案或 crate,無需手動編譯;預設提供 pyo3 整合並自動產生 pyo3 綁定程式碼
- pyo3-arrow 為 pyo3 提供的輕量 Apache Arrow 整合
- pyo3-bytes
bytes與 pyo3 的整合 - pyo3-object_store
object_store與pyo3的整合
範例
- anise A modern, high-performance toolkit for spacecraft mission design, notably used to help softly land Firefly Blue Ghost on the Moon on 02 Feb 2025.
- arro3 連結 Rust arrow crate 的最小化 Apache Arrow Python 函式庫
- arro3-compute
arro3-compute - arro3-core
arro3-core - arro3-io
arro3-io
- arro3-compute
- bed-reader 簡潔且高效地讀寫 PLINK BED 格式
- 展示 Rayon/ndarray::parallel(包含錯誤擷取與控制執行緒數)、Python 型別到 Rust 泛型,以及 GitHub Actions
- blake3-py BLAKE3 密碼雜湊函式的 Python 綁定
- 在 GitHub Actions 上針對 macOS、Linux、Windows 進行平行化建置,包含 free-threaded 3.13t 的 wheel。
- cellular_raza 以細胞代理為基礎的模擬框架,用於從零構建複雜模型
- connector-x 在 Rust 與 Python 中將資料從資料庫載入到 DataFrame 的高速函式庫
- cryptography 部分功能以 Rust 實作的 Python 密碼學函式庫
- css-inline 以 Rust 實作的 Python CSS 內嵌工具
- datafusion-python 綁定 Apache Arrow 記憶體內查詢引擎 DataFusion 的 Python 函式庫
- deltalake-python 基於 delta-rs 並整合 Pandas 的原生 Delta Lake Python 綁定
- fastbloom 以 Rust 實作的快速 bloom filter | counting bloom filter,同時支援 Rust 與 Python
- fastuuid Rust UUID 函式庫的 Python 綁定
- fast-paseto 高效能 PASETO(Platform-Agnostic Security Tokens)實作,提供 Python 綁定
- feos 以 Rust 進行極速熱力學建模,並提供完善的 Python 介面
- finalytics Rust | Python 投資分析函式庫
- forust 以 Rust 撰寫的輕量級梯度提升決策樹函式庫
- geo-index 提供緊湊、不可變、零拷貝空間索引的 Rust crate 與 Python 函式庫
- granian 供 Python 應用使用的 Rust HTTP 伺服器
- haem 用於生物資訊問題的 Python 函式庫
- hifitime A high fidelity time management library for engineering and scientific applications where general relativity and time dilation matter.
- html2text-rs 將 HTML 轉為標記或純文字的 Python 函式庫
- html-py-ever 透過 kuchiki 使用 html5ever 加速 HTML 解析與 CSS 選取
- hudi-rs Apache Hudi 的原生 Rust 實作,並提供 C++ 與 Python API 綁定
- inline-python 在 Rust 程式碼中直接內嵌 Python 程式碼
- johnnycanencrypt 支援 Yubikey 的 OpenPGP 函式庫。
- jsonschema 高效能的 Python JSON Schema 驗證器
- mocpy 天文 Python 函式庫,提供用於描述單位球面上任意覆蓋區域的資料結構
- obstore 以 Rust 驅動、最簡潔且高吞吐量的 Python 介面,可存取 Amazon S3、Google Cloud Storage、Azure Storage 與其他相容 S3 的 API
- opendal 資料存取層,可讓使用者以統一方式輕鬆且高效地從各種儲存服務取回資料
- orjson 快速的 Python JSON 函式庫
- ormsgpack 快速的 Python msgpack 函式庫
- polars Rust | Python | Node.js 的高速多執行緒 DataFrame 函式庫
- pycrdt Rust CRDT 實作 Yrs 的 Python 綁定
- pydantic-core 以 Rust 撰寫的 pydantic 核心驗證邏輯
- primp 可透過模擬標頭與 TLS/JA3/JA4/HTTP2 指紋來偽裝瀏覽器的最快 Python HTTP 用戶端
- radiate:用於遺傳程式設計與演化演算法的高效能演化引擎
- rateslib 使用 Rust 擴充的 Python 固定收益函式庫
- river Python 的線上機器學習,計算量大的統計演算法以 Rust 實作
- robyn 具備 Rust runtime 的超高速非同步 Python Web 框架。
- rust-python-coverage 含 Rust 與 Python 自動化測試覆蓋的 PyO3 專案範例
- rnet 帶有黑魔法的非同步 Python HTTP 用戶端
- sail 在相容 Apache Spark 的前提下統一串流、批次與 AI 工作負載
- tiktoken 可搭配 OpenAI 模型使用的快速 BPE 分詞器
- tokenizers Rust 撰寫的 Hugging Face tokenizers(NLP)的 Python 綁定
- tzfpy 快速將經緯度轉為時區名稱的軟體包
- toml-rs 以 Rust 撰寫的 Python 高效能 TOML v1.0.0 與 v1.1.0 解析器
- utiles 快速的 Python 網路地圖磚工具
文章及其他媒體
- (影片) 在 Free-Threaded 與一般 Python 3.13 中使用 Rust - 2025/06/04
- (影片) 五年探索 Rust 在 Python 中的技巧與心得 - 2025/02/26
- (Podcast) Bridging Python and Rust:訪談 PyO3 維護者 David Hewitt - 2024/08/30
- (影片) PyO3:從 Python 到 Rust 再回來 - 2024/07/03
- 用 Rust 解析 Python AST 快 20 倍 - 2024/06/17
- (影片) Python 如何透過 PyO3 結合 Rust - 2024/05/18
- (影片) 結合 Rust 與 Python:兩全其美? - 2024/03/01
- (影片) 使用 PyO3 以 Rust 擴充 Python - 2023/12/16
- 一週 PyO3 + rust-numpy(如何讓資料管線加速 X 倍) - 2023/06/06
- (Podcast) PyO3 與 David Hewitt - 2023/05/19
- 不到 100 行 Rust 讓 Python 快 100 倍 - 2023/03/28
- Pydantic V2 如何運用 Rust 的超能力 - 2023/02/04
- 我們如何使用 PyO3 以 Rust 擴充 River 統計模組 - 2022/12/23
- 以 Rust 撰寫 Python 擴充的九條規則 - 2021/12/31
- 使用 PyO3 從 Python 呼叫 Rust - 2021/11/18
- davidhewitt 在 Rust Manchester meetup 的 2021 演講 - 2021/08/19
- 逐步將小型 Python 專案移植到 Rust - 2021/04/29
- Vortexa - 將 Rust 整合進 Python - 2021/04/12
- 以 Rust 撰寫並發布 Python 模組 - 2020/08/02
參與貢獻
歡迎大家參與 PyO3!你可以用許多方式支持專案,例如:
- 在 GitHub 與 Discord 協助 PyO3 使用者解決問題
- 改善文件
- 撰寫功能與修復錯誤
- 發表如何使用 PyO3 的部落格與範例
若你願意投入時間參與 PyO3,但不確定從哪裡開始,可參考我們的貢獻說明與架構指南取得更多資源。
如果你沒有時間親自貢獻,但仍想支持專案的長期發展,部分維護者有 GitHub 贊助頁面:
授權條款
PyO3 採用 Apache-2.0 授權 或 MIT 授權,可自行選擇。
Python 採用 Python License 授權。
除非你明確另行說明,否則你提交且意圖納入 PyO3 的任何貢獻(依 Apache License 定義)將採用上述雙重授權,不附加任何額外條款或條件。