#stderr #stdout #stdio #redirect #silent #io-read

shh

Silence stderr and stdout, optionally rerouting it

5 releases (2 stable)

1.0.1 Jan 19, 2020
1.0.0 Mar 16, 2019
0.1.2 Mar 16, 2019
0.1.1 Mar 16, 2019
0.1.0 Mar 16, 2019

#1 in #silent

Download history 325/week @ 2024-07-22 294/week @ 2024-07-29 336/week @ 2024-08-05 378/week @ 2024-08-12 255/week @ 2024-08-19 289/week @ 2024-08-26 256/week @ 2024-09-02 221/week @ 2024-09-09 334/week @ 2024-09-16 611/week @ 2024-09-23 543/week @ 2024-09-30 333/week @ 2024-10-07 363/week @ 2024-10-14 385/week @ 2024-10-21 238/week @ 2024-10-28 577/week @ 2024-11-04

1,568 downloads per month
Used in 9 crates (4 directly)

MIT license

17KB
272 lines

(Rust) Silence stderr and stdout, optionally rerouting it.

Stdout Gagging

println!("STDOUT GAGGING", );
println!("you will see this");
let shh = shh::stdout().unwrap();
println!("but not this");
drop(shh);
println!("and this");

Stderr Gagging

println!("STDERR GAGGING", );
eprintln!("you will see this");
let shh = shh::stderr().unwrap();
eprintln!("but not this");
drop(shh);
eprintln!("and this");

Redirecting Example

println!("REDIRECTING", );
use std::io::{Read, Write};

std::thread::spawn(move || {
    let mut shh = shh::stdout().unwrap();
    let mut stderr = std::io::stderr();
    loop {
        let mut buf = Vec::new();
        shh.read_to_end(&mut buf).unwrap();
        stderr.write_all(&buf).unwrap();
    }
});

println!("This should be printed on stderr");
eprintln!("This will be printed on stderr as well");

// This will exit and close the spawned thread.
// In most cases you will want to setup a channel and send a break signal to the loop,
// and then join the thread back into it once you are finished.

Scoping

The struct Shh implements the Drop trait. Upon going out of scope, the redirection is reset and resources are cleaned up. A Shh will only last for the scope, and where no local variable is used, the silencing will not work.

Example - Silencing Dropped Early

println!("you will see this");
shh::stdout().unwrap();        // Shh struct is created, and dropped, here
println!("and expect not to see this, but you will");

To fix this, just assign a local variable

println!("you will see this");
let shh = shh::stdout().unwrap();        // Shh struct is created here
println!("and expect not to see this");
drop(shh);    // and dropped here
println!("now it works!");

Dependencies

~220KB