Skip to content

Question: How to capture the stdout of the python interpreter #1918

Answered by birkenfeld
sebschmi asked this question in Questions
Discussion options

You must be logged in to vote

Ok, now that I can actually run and test something, here's an example:

use pyo3::prelude::*;

#[pyclass]
struct LoggingStdout;

#[pymethods]
impl LoggingStdout {
    fn write(&self, data: &str) {
        println!("stdout from python: {:?}", data);
    }
}

fn main() -> PyResult<()> {
    Python::with_gil(|py| {
        let sys = py.import("sys")?;
        sys.setattr("stdout", LoggingStdout.into_py(py))?;
        py.run("print('some', 'output')", None, None)?;
        Ok(())
    })
}

The output will be:

stdout from python: "some"
stdout from python: " "
stdout from python: "output"
stdout from python: "\n"

As you can see, depending on how the output is written to sys.stdout by the Python…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by davidhewitt
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2 participants
Converted from issue

This discussion was converted from issue #1872 on October 13, 2021 20:51.