【发布时间】:2021-08-10 15:35:17
【问题描述】:
在遵循有关编译 Rust 库以进一步从 Python 导入的各种教程(我已经尝试过 PyO3 和 rust-cpython)时,我已经能够构建一个简单的库并成功地从我的 main.py 导入它和交互式 Python shell。
但是,在尝试测试纯 Python 和我的 Rust 库并进行基准测试时,我总是遇到导入错误:
_____________________________________________ ERROR collecting main.py _____________________________________________
ImportError while importing test module '/Users/xxx/pyo3/sumlib/main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/Users/xxx/.pyenv/versions/3.8.2/lib/python3.8/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
main.py:1: in <module>
import sumlib
E ModuleNotFoundError: No module named 'sumlib'
同样,该库可以很好地从主 python 文件和交互式 shell(如 IPython)导入。
我在 macOS Big Sur 上,使用pyenv 安装了 Python 3.8。这是我的Cargo.toml:
[package]
name = "sumlib"
version = "0.1.0"
edition = "2018"
[lib]
name = "sumlib"
# "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", "rlib"]
[dependencies.pyo3]
version = "0.14.2"
features = ["extension-module"]
从PyO3 和rust-cpython 到相同的结果,其他一切都非常简单。
【问题讨论】:
-
你是如何打包你的模块的?
PyO3文档中有 a section on packaging tools。 -
我基本上是按照说明操作的,比如我用了
maturin+PyO3的虚拟环境,它生成并安装了有效的轮子,但它似乎仍然无法导入我编译的动态库特别来自pytest。