如何从Rust调用Python异步函数?

2024-06-16 12:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读过这个答案,我想做的与此相反

我想调用Python异步函数并在tokio的运行时等待它。可能吗

我已经尝试了一些,但是我在输出中遇到了一个错误

以下是我的python文件的外观:

import rust_package

async def h():
    print("message from coroutine")


print("Hello world")
s = rust_package.Server()
s.start(h)

这就是我的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).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        pyo3_asyncio::tokio::init(rt);
        Python::with_gil(|py| {
            pyo3_asyncio::tokio::run_until_complete(py, async move {
                tokio::time::sleep(Duration::from_secs(1)).await;
                f.await.unwrap();
                Ok(())
            })
            .unwrap();
        });
}

#[pymodule]
pub fn roadrunner(py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_class::<Server>()?;
    pyo3_asyncio::try_init(py);
    Ok(())
}

我得到以下错误:

Hello world
Exception in callback <builtins.PyEnsureFuture object a
t 0x10bc1bd20>()
handle: <Handle <builtins.PyEnsureFuture object at 0x10
bc1bd20>()>
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/P
ython.framework/Versions/3.9/lib/python3.9/asyncio/even
ts.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/P
ython.framework/Versions/3.9/lib/python3.9/asyncio/task
s.py", line 679, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or
an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitab
le is required

很明显,我正在传递一个异步函数并将其转换为将来的函数。我想不出哪里出了问题。我已经多次阅读了pyo3-async的文档,但仍然无法理解它。 我真的很感谢你的帮助

提前谢谢


Tags: 函数runpyselfasyncionewasyncserver
1条回答
网友
1楼 · 发布于 2024-06-16 12:30:42

根据@sebpuetz的建议

我所需要的就是 改变

s.start(h)

s.start(h())

因为h本身只是一个函数h()是一个协程,它是必需的项

相关问题 更多 >