当前位置:首页>python>rustimport,你只要在 Python 里敲一行代码,就能自动把对应的 Rust 源码编译成 扩展模块

rustimport,你只要在 Python 里敲一行代码,就能自动把对应的 Rust 源码编译成 扩展模块

  • 2026-09-10 08:16:20
rustimport,你只要在 Python 里敲一行代码,就能自动把对应的 Rust 源码编译成 扩展模块

什么是 rustimportrustimport 是一个神奇的小工具,你只要在 Python 里敲一行 import somecode,就能自动把对应的 Rust 源码编译成 Python 扩展模块,完全不用手动写 Cargo.toml、setup.py 或者敲 cargo build。想想看,以前要把 Rust 绑到 Python 得跑一堆脚本、写一堆配置,现在直接开写 Rust 代码就行,敲一下 import rustimport.import_hook,然后直接 import your_module,秒编译、秒加载,简直不要太爽。


它为啥这么牛

  1. 1. 零配置:只要在 Rust 文件第一行写 // rustimport:pyo3,剩下就交给 rustimport。
  2. 2. 自动热重载:每次 import 会检查源码 checksum,只有改了才重编译,不改就秒过。
  3. 3. 支持单文件 & 完整 Crate:想快速写个小函数就单文件,想写复杂逻辑就用 python -m rustimport new my_crate。
  4. 4. 兼容 Jupyter:在笔记本里 %load_ext rustimport,然后用 %%rustimport 一键编译。
  5. 5. CI/CD 集成友好:提供 python -m rustimport build --release,可以预先构建好 release 二进制,生产环境直接部署。

那些烦人的痛点 & rustimport 的解决方案

  • • 传统 Python + Rust:
    • • 手动写绑定代码,貌似写完就能用,却总调不过去。
    • • 每改一行都得跑一遍 cargo build,效率低下。
    • • CI 环境要装 Rust 工具链,部署包大还慢。
  • • rustimport 帮你搞定:
    • • 绑定自动生成。只管写 #[pyfunction] fn foo(),模块导出也自动加好了。
    • • 增量编译+缓存。只有代码变了才编译,且用临时目录缓存,重启后也能续命(可自定义缓存目录)。
    • • Release 模式编译。CI 里一条命令就能把所有 .rs 和 Crate build 完,部署环境零依赖。

安装和快速上手

pip install rustimport
  1. 1. 创建单文件扩展:
    python -m rustimport new my_ext.rs
  2. 2. 写点 Rust 代码,记得第一行加入模板指令:
    // rustimport:pyo3use pyo3::prelude::*;#[pyfunction]fnsquare(x:i32)->i32{    x * x}
  3. 3. 在 Python 里:
    import rustimport.import_hookimport my_ext       # 第一次会编译,之后变源码才重编译print(my_ext.square(9))# 81
  4. 4. Jupyter 中:
    %load_ext rustimport%%rustimport --releaseuse pyo3::prelude::*;#[pyfunction]fn hello()->String{"Hello from Rust!".into()}

优缺点大盘点

优点
缺点/注意事项
极简体验:零配置,一行编译导入
第一次编译时间偏长,后续增量快
自动增量编译,热重载
只支持 Rust + Python,其他语言不适用
单文件 & Crate 都能玩
想用自定义 Cargo 配置需要自己写 Cargo.toml
支持 Jupyter,CI 一键预编译
Release 模式要提前 build,否则异常
环境变量灵活定制,如强制重建等
macOS 链接 args 虽自动,但 pyo3 版本得跟上

总结大体来说,rustimport 就是把 Python 导入扩展模块、Rust 编译这两个步骤,合二为一,极大提高了 Rust + Python 混合开发的效率。平时写脚本觉得 Python 太慢的,或者有现成 Rust 算法想拿来用的,用它就对了。唯一需要忍受的是第一次编译可能有点久,但爽爽的后续增量编译绝对能弥补这点小缺憾。想兼顾开发体验和性能,rustimport 基本就是神器级别的存在。

项目地址:https/github.com/mityax/rustimport

最新文章

随机文章