Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kurtlawrence/shh
(Rust) Silence stderr and stdout, optionally rerouting it.
https://github.com/kurtlawrence/shh
Last synced: about 2 months ago
JSON representation
(Rust) Silence stderr and stdout, optionally rerouting it.
- Host: GitHub
- URL: https://github.com/kurtlawrence/shh
- Owner: kurtlawrence
- License: mit
- Created: 2019-03-15T18:48:00.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2020-04-21T02:16:59.000Z (over 4 years ago)
- Last Synced: 2024-10-11T01:55:31.629Z (3 months ago)
- Language: Rust
- Size: 26.4 KB
- Stars: 16
- Watchers: 4
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
(Rust) Silence stderr and stdout, optionally rerouting it.
Stdout Gagging
```rust
println!("STDOUT GAGGING", );
println!("you will see this");
let shh = shh::stdout().unwrap();
println!("but not this");
drop(shh);
println!("and this");
```Stderr Gagging
```rust
println!("STDERR GAGGING", );
eprintln!("you will see this");
let shh = shh::stderr().unwrap();
eprintln!("but not this");
drop(shh);
eprintln!("and this");
```Redirecting Example
```rust
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
```rust
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
```rust
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!");
```