RustPyO3创建死锁/从python调用异步函数后变得无响应

2024-05-15 10:49:48 发布

您现在位置: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库,然后使用tokio运行时调用它。 当我执行python文件时,会出现死锁,因为即使^C也没有退出它

请让我知道如何正确地等待rust中的python函数

提前谢谢


Tags: pytestselfasyncionewasyncserverrust