Filter out ANSI escape codes from child process stdout/stderr

⚓ Rust    📅 2026-02-20    👤 surdeus    👁️ 1      

surdeus

If I am spawning a child process like this:

let mut child = Command::new("my_custom_command")
    .args(&args)
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .stderr(Stdio::inherit())
    .spawn()
    .context(format!(
        "Failed to execute my_custom_command."
    ))?;

The issue is that if the stderr of the untrusted process includes ANSI escape codes it can hijack my terminal output. So I want to filter specific ANSI codes.

let mut child = Command::new("my_custom_command")
    .args(&args)
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .stderr(Stdio::inherit())
    .spawn()
    .context(format!(
        "Failed to execute my_custom_command."
    ))?;

let stderr_reader = child.stderr.take().map(|mut stderr| {
    std::thread::spawn(move || -> Result<()> {
        // ....
        let out = filter_ansi_escape_code_logic(...)
       // ....
    })
});

This approach seems to work to filter out ANSI escape codes, but is it the best way? Is it efficient to do the same for stdout too? What about making a own std::io::pipe() instead of using threads?

1 post - 1 participant

Read full topic

🏷️ Rust_feed