我正在开发一个视频游戏,在这个游戏中,我需要从Python中设置Rust对象(比如,添加一个带有texture:"", coords:"", text:"", action:""的按钮)。
我使用pyo3机箱来链接。我成功地从我的Rust代码中调用了Python脚本,但是我找不到如何从Python文件中调用Rust函数。
执行我的Python脚本的生锈代码:
fn main() -> PyResult<()> {
let gil = Python::acquire_gil();
let py = gil.python();
let script = fs::read_to_string("deep_hello.py")?;
println!("RUNNING :\n[\n{}]", script);
py.run(&script, None, None)
}我想从Python脚本中调用的铁锈函数:
/// hello_from_rust(/)
/// --
///
/// This function prints hello because she is very nice.
#[pyfunction]
fn hello_from_rust() {
println!("Hello from rust from python !");
}我的Python脚本:
hello_from_rust()我得到了这个输出:
RUNNING :
[
hello_from_rust()
]
Error: PyErr { type: Py(0x7f9cdd1e9580, PhantomData) }发布于 2020-05-24 16:24:36
如果我正确理解了您的问题,那么您要做的工作包括三个步骤:
hello_from_rust()的Python模块deep_hello.py中使用deep_hello.py。我没有能够完全再现你的问题,但似乎你的问题的根源可能是在第一或第二步。
使用PyO3定义Python模块
在PyO3文档中,我希望hello_from_rust()位于一个Rust文件中,该文件定义了一个类似于以下内容的Python模块:
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
#[pyfunction]
fn hello_from_rust() {
println!("Hello from rust from python !");
}
#[pymodule]
fn hello_module(py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(hello_from_rust));
Ok(())
}您可以使用Cargo将其构建到Python模块中(请参阅这里;根据操作系统的不同,说明略有不同),并将生成的.so (Linux或MacOS)或.pyd (.pyd)文件放在与您的Python脚本相同的目录中。
备注
您必须创建一个类似于hello_module的函数来初始化您的Python模块。如果不这样做,您的Rust库可能仍然会编译,但是您将无法导入hello_from_rust。
使用新的Python模块
您的deep_hello.py脚本应该如下所示:
import hello_module
hello_module.hello_from_rust()确保.so或.pyd文件在PYTHON_PATH中是可访问的(例如将其放在与脚本相同的目录中),使用Python>= 3.5运行deep_hello.py应该可以工作。(请注意,您的系统Python可能是Python 2,因此您可能希望使用一个较新版本的Python创建一个Anaconda环境,并在其中工作。)
对我来说,遵循这些步骤是成功的。
(ruspy) ruspy $ python deep_hello.py
Hello from rust from python !备注
确保您记得在Python中使用import hello_module!您的PyErr返回的py.run(&script, None, None)使我怀疑这个问题是否真的存在于您的hello_from_rust()脚本中,实际上,即使您正确地组合了deep_hello模块,我也希望没有前面的from deep_hello import *的hello_from_rust()会生成NameError。
从Rust调用Python的Rust
我不完全确定您为什么要这样做,但是现在您应该能够从Rust运行deep_hello.py了。
https://stackoverflow.com/questions/56803942
复制相似问题