wasmtime-py:由 Wasmtime 提供动力的 Python WebAssembly 运行时
What is wasmtime‑py?
WebAssembly (WASM) 是一种针对速度、安全性和可移植性而设计的二进制指令格式。它可以让你把用 C、Rust 或 AssemblyScript 编写的代码编译成一个沙箱化模块,在多种运行时中运行。
wasmtime‑py 是 Wasmtime 引擎的 Python 包装器,Bytecode Alliance 开发的行业级执行引擎。它将 Wasmtime 转变为一等 Python 包,让开发者能够直接在 Python 代码中编译、实例化并运行 WASM 模块。
主要特性:
- 无依赖 – 包装器捆绑静态链接的 Wasmtime 二进制文件;不需要外部 C 库。
- Python‑友好 API – 将 WASM 模块作为普通 Python 对象暴露,带有清晰的错误处理。
- 组件支持 – 新的“组件模型”可像核心模块一样使用。
- 跨平台 – 支持 Windows、macOS 和 Linux 的 x86_64 与 arm64。
为什么使用 wasmtime‑py?
如果你:
- 需要在 Rust 或 C 编写的性能关键计算上跑少量代码。
- 想要在不重启 Python 进程的情况下对第三方代码进行沙箱化。
- 正在构建一个混合 Python 与 WASM 模块的多语言服务器。
- 寻找一个易于通过
pip安装的极简运行时。
则 wasmtime‑py 非常合适。与捆绑 VM 与众多运行时 crate 的重量级运行时不同,该库保持占用小(磁盘小于 5 MiB),同时提供熟悉的 Python API。
安装
pip install wasmtime
该包会自动检测你的平台并下载匹配的 Wasmtime 二进制文件。若想使用自定义构建或指定某一发行版的预编译 wheel,可指明版本:
pip install "wasmtime==0.30.0"
支持的 Python 版本:3.9+。
快速上手 – 编译并运行一个模块
from wasmtime import Store, Module, Instance, Func, FuncType
store = Store()
module = Module(store.engine, """
(module
(func $hello (import \"\" \"hello\"))
(func (export \"run\") (call $hello))
)"")
# Define the imported host function
def say_hello():
print("Hello from Python!")
hello = Func(store, FuncType([], []), say_hello)
# Instantiate the module, passing the host function
instance = Instance(store, module, [hello])
run = instance.exports(store)["run"]
run(store)
输出:
Hello from Python!
导入预编译的 WASM 模块
WASMTIME‑PY 能够自动加载作为 Python 模块存在的已编译模块。加载器适用于遵循 PEP 420 命名空间包规范的文件。
# 假设你已把 my_module.wasm 编译完成并与此脚本放在同一目录
import wasmtime.loader # registers the custom loader
import my_module
my_module.run()
幕后,加载器会在首次导入时编译 .wasm 文件,并缓存得到的 Instance。
使用组件
组件模型在核心 WebAssembly 基础上扩展了更丰富的导入/导出和类型安全。它完全受支持:
from wasmtime import Store, Component
store = Store()
component = Component(store.engine, """
(component "hello"
(import "hello" (func (type 0)))
(export "hello" (func 0)))
)"")
# Component instances take a list of host functions matching the component's import type
instance = component.instantiate(store, [hello])
instance.exports(store)["hello"](store)
贡献
wasmtime‑py 在 Apache‑2.0 许可证下开源。欢迎贡献:
- Fork 代码仓库。
- 创建功能分支。
- 用
pytest运行测试套件。 - 提交带有清晰描述的 Pull Request。
- 审核遵循标准 GitHub 工作流。
请查看 CONTRIBUTING.md 了解指南与编码规范。
未来计划
- 与核心 Wasmtime 发布同步的增量 API 更改。
- 对 WASI(WebAssembly 系统接口)的支持,以运行更复杂的应用。
- 与流行 Python 异步框架更好的集成。
- 针对数据科学与机器学习工作负载的新示例。
总结
wasmtime‑py 为将 WebAssembly 逻辑嵌入 Python 应用提供了强大而轻量的工具。无论你是在原型化新语言特性、沙箱化不可信代码,还是构建多语言微服务,都能以最小运行时开销(除 Wasmtime 引擎外)简单嵌入。试一试,探索丰富文档,贡献 WebAssembly Python 生态的成长。