gpt4 book ai didi

python - 在 Rust 中使用 pyo3 构建 python 库时出现错误 "no py in the root"

转载 作者:行者123 更新时间:2023-11-29 08:15:14 27 4
gpt4 key购买 nike

我的环境

  • Ubuntu 18.04
  • Rust 1.39.0-每晚
  • python 3.7.3

我想做的和遇到的问题

我想为 python 编写一个库。作为练习,我尝试了文档中的代码。

cargo .toml

[package]
name = "example"
version = "0.1.0"
authors = ["Yudai Hayashi"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "example"
crate-type = ["cdylib"]

[dependencies]

[dependencies.pyo3]
version = "*"
features = ["extension-module"]

源码/lib.rs

#![feature(proc_macro, specialization)]

extern crate pyo3;
use pyo3::{py, PyResult, Python, PyModule};

use pyo3::py::modinit as pymodinit;

// add bindings to the generated python module
// N.B: names: "librust2py" must be the name of the `.so` or `.pyd` file
/// This module is implemented in Rust.
#[pymodinit(rust2py)]
fn init_mod(py: Python, m: &PyModule) -> PyResult<()> {

#[pyfn(m, "sum_as_string")]
// pyo3 aware function. All of our python interface could be declared in a separate module.
// Note that the `#[pyfn()]` annotation automatically converts the arguments from
// Python objects to Rust values; and the Rust return value back into a Python object.
fn sum_as_string_py(_: Python, a:i64, b:i64) -> PyResult<String> {
let out = sum_as_string(a, b);
Ok(out)
}

Ok(())
}

// logic implemented as a normal Rust function
fn sum_as_string(a:i64, b:i64) -> String {
format!("{}", a + b).to_string()
}

当我构建这个程序时,我遇到了一些错误。

error[E0432]: unresolved import `pyo3::py`
--> src/lib.rs:4:12
|
4 | use pyo3::{py, PyResult, Python, PyModule};
| ^^
| |
| no `py` in the root
| help: a similar name exists in the module: `Py`

error[E0432]: unresolved import `pyo3::py`
--> src/lib.rs:6:11
|
6 | use pyo3::py::modinit as pymodinit;
| ^^ could not find `py` in `pyo3`

error: cannot determine resolution for the attribute macro `pymodinit`
--> src/lib.rs:11:3
|
11 | #[pymodinit(rust2py)]
| ^^^^^^^^^
|
= note: import resolution is stuck, try simplifying macro imports

error: cannot find attribute macro `pyfn` in this scope
--> src/lib.rs:14:7
|
14 | #[pyfn(m, "sum_as_string")]
| ^^^^

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0432`.
error: Could not compile `example`.

此错误消息表示在 pyo3 模块中没有“py”。我查找了此错误消息,但找不到类似的错误。

如何处理这个问题?

最佳答案

no mod called py在最新版本的 pyo3 中。您找到了与旧版本库相关的文档或示例。具有此 mod 的最后一个版本是 0.2.7。

如果您除了运行代码之外没有其他兴趣,请在您的 Cargo.toml 依赖项中将您需要的 pyo3 版本设置为 0.2.7 并且它应该开箱即用(粗略一瞥确认所有符号似乎都存在于该版本中)。

如果您想实际调查较新的版本,the new documentation有最新的例子。

关于python - 在 Rust 中使用 pyo3 构建 python 库时出现错误 "no py in the root",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936617/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com