How to capture the stdout of the Python interpreter inside the Rust program when using the pyo3 crate

Viewed 72

I am using the Rust bindings of the Python interpreter provided by the crate pyo3.

I have the following code:

fn run(script: &str) {
    Python::with_gil(|py| py.run(script, None, None)).unwrap();
}

fn main() {
    run("print('abc')");
}

I would like everything written to stdout by script to be captured and accessible from my Rust program, instead of being written to the actual stdout.

That is, in this example, the program should not actually print abc, but it should store it somewhere in memory and hand me over a reference, owned string or something.

Ideally this would work via a callback, handing me over lines of output one-by-one as they are created.

0 Answers
Related