Skip to content

Commit f907be0

Browse files
committed
fix asyncio loop
1 parent 307bef9 commit f907be0

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,6 @@ pub struct PyRunner {
9292
sender: mpsc::Sender<PyCommand>,
9393
}
9494

95-
9695
impl Default for PyRunner {
9796
fn default() -> Self {
9897
PyRunner::new()
@@ -569,6 +568,7 @@ async def add_and_sleep(a, b, sleep_time):
569568
let result2 =
570569
executor.call_async_function("add_and_sleep", vec![5.into(), 10.into(), 0.1.into()]);
571570
let (result1, result2) = tokio::join!(result1, result2);
571+
// The order of execution is guaranteed by the last timing parameters
572572
assert_eq!(result1.unwrap(), Value::Number(17.into()));
573573
assert_eq!(result2.unwrap(), Value::Number(16.into()));
574574
}

src/pyo3_runner.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,18 @@ async fn handle_call_async_function(
154154
let t_args = vec_to_py_tuple(&py, args)?;
155155
let coroutine = func.call1(t_args)?;
156156

157-
let asyncio = py.import("asyncio")?;
158-
let loop_obj = asyncio.call_method0("new_event_loop")?;
159-
asyncio.call_method1("set_event_loop", (loop_obj.clone(),))?;
157+
let asyncio = py.import("asyncio")?; // py.import_bound("asyncio")? in newer pyo3
158+
let loop_obj = match asyncio.call_method0("get_running_loop") {
159+
Ok(loop_obj) => loop_obj,
160+
Err(_) => {
161+
// If no loop is running, create a new one and set it.
162+
let new_loop = asyncio.call_method0("new_event_loop")?;
163+
asyncio.call_method1("set_event_loop", (new_loop.clone(),))?;
164+
new_loop
165+
}
166+
};
167+
160168
let result = loop_obj.call_method1("run_until_complete", (coroutine,))?;
161-
loop_obj.call_method0("close")?;
162169

163170
py_any_to_json(&result)
164171
});

0 commit comments

Comments
 (0)