Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cross-platform way to check if stdout is being piped into another program in Rust?

Tags:

pipe

rust

tty

I'd like to disable colors when the output is piped somewhere else than a terminal.

like image 273
Narigo Avatar asked Feb 04 '26 07:02

Narigo


2 Answers

As of Rust 1.70, std::io::IsTerminal is available:

use std::io::IsTerminal;

fn main() {
    dbg!(std::io::stdout().is_terminal());
}

Alternatively, crossterm has a is_tty() method, and there's also the is-terminal crate (a maintained fork of atty).

like image 58
Wilfred Hughes Avatar answered Feb 05 '26 22:02

Wilfred Hughes


Translated into the POSIX language, your question would be: "is stdout not a TTY", so the answer on *nix can be obtained by !isatty(STDOUT_FILENO). The libc crate can be used to call this from Rust.

On Windows, it's complicated, so you're better off using the atty crate.

[edit] You can use the atty crate on Linux as well, making it a convenient solution for cross-platform programs.

like image 28
3 revs, 2 users 71%Nickolay Avatar answered Feb 06 '26 00:02

3 revs, 2 users 71%Nickolay