File: test_async_std_run_forever.rs

package info (click to toggle)
rust-pyo3-async-runtimes 0.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 448 kB
  • sloc: makefile: 2
file content (48 lines) | stat: -rw-r--r-- 1,408 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::time::Duration;

use pyo3::prelude::*;

fn dump_err(py: Python, e: PyErr) {
    // We can't display Python exceptions via std::fmt::Display,
    // so print the error here manually.
    e.print_and_set_sys_last_vars(py);
}

fn main() {
    pyo3::prepare_freethreaded_python();

    Python::with_gil(|py| {
        let asyncio = py.import("asyncio")?;

        let event_loop = asyncio.call_method0("new_event_loop")?;
        asyncio.call_method1("set_event_loop", (&event_loop,))?;

        let event_loop_hdl = PyObject::from(event_loop.clone());

        async_std::task::spawn(async move {
            async_std::task::sleep(Duration::from_secs(1)).await;

            Python::with_gil(|py| {
                event_loop_hdl
                    .bind(py)
                    .call_method1(
                        "call_soon_threadsafe",
                        (event_loop_hdl
                            .bind(py)
                            .getattr("stop")
                            .map_err(|e| dump_err(py, e))
                            .unwrap(),),
                    )
                    .map_err(|e| dump_err(py, e))
                    .unwrap();
            })
        });

        event_loop.call_method0("run_forever")?;

        println!("test test_async_std_run_forever ... ok");
        Ok(())
    })
    .map_err(|e| Python::with_gil(|py| dump_err(py, e)))
    .unwrap()
}