python - Rust-PyO3 在从 python 调用异步函数后创建死锁/变得无响应
问题描述
lib.rs
#[pyclass]
struct Server {}
#[pymethods]
impl Server {
#[new]
fn new() -> Self {
Self {}
}
fn start(mut self_: PyRefMut<Self>, test: &PyAny) {
let f = pyo3_asyncio::into_future(test);
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let x = f.unwrap().await;
match &x {
Ok(_) => (),
Err(v) => println!("{}", v),
}
});
}
}
#[pymodule]
pub fn roadrunner(py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<Server>()?;
pyo3_asyncio::try_init(py);
Ok(())
}
#index.py
import rust_package
async def h():
print("hhh")
print("Hello world")
s = roadrunner.Server()
s.start(h)
以上是我在项目中使用的 python 和 rust 文件。我正在尝试将异步函数作为参数传递给我的 rust lib,然后使用 tokio 运行时调用它。当我执行我的 python 文件时,我遇到了死锁,因为甚至^C
没有退出它。
请让我知道如何正确等待 rust 中的 python 函数。
提前致谢。
解决方案
推荐阅读
- java - 线程“主”org.openqa.selenium.WebDriverException 中的异常:驱动程序服务器进程过早死亡
- java - 如何将 LWJGL 游戏场景渲染到 ByteBuffer?
- google-cloud-firestore - 自定义 Rest API 和 Firestore 数据库
- slack - Slack API:有没有办法确定哪个用户点击了交互式消息中的按钮?
- javascript - 如何仅从对象数组的每个对象返回对象值?
- python - TypeError:定义自定义迭代器时 INT 对象不可迭代
- vue.js - 操作后重定向用户
- html - 如果有人这样做,有没有办法打破每一个字?
- javascript - 生成列表中以前不存在的随机数
- r - 如何从闪亮的点击中获取x类别