Function pyo3_asyncio::into_future_with_locals
source · pub fn into_future_with_locals(
locals: &TaskLocals,
awaitable: &PyAny
) -> PyResult<impl Future<Output = PyResult<PyObject>> + Send>Expand description
Convert a Python awaitable into a Rust Future
This function converts the awaitable into a Python Task using run_coroutine_threadsafe. A
completion handler sends the result of this Task through a
futures::channel::oneshot::Sender<PyResult<PyObject>> and the future returned by this function
simply awaits the result through the futures::channel::oneshot::Receiver<PyResult<PyObject>>.
Arguments
locals- The Python event loop and context to be used for the provided awaitableawaitable- The Pythonawaitableto be converted
Examples
use std::time::Duration;
use pyo3::prelude::*;
const PYTHON_CODE: &'static str = r#"
import asyncio
async def py_sleep(duration):
await asyncio.sleep(duration)
"#;
async fn py_sleep(seconds: f32) -> PyResult<()> {
let test_mod = Python::with_gil(|py| -> PyResult<PyObject> {
Ok(
PyModule::from_code(
py,
PYTHON_CODE,
"test_into_future/test_mod.py",
"test_mod"
)?
.into()
)
})?;
Python::with_gil(|py| {
pyo3_asyncio::into_future_with_locals(
&pyo3_asyncio::tokio::get_current_locals(py)?,
test_mod
.call_method1(py, "py_sleep", (seconds.into_py(py),))?
.as_ref(py),
)
})?
.await?;
Ok(())
}