pub trait IsTerminal: Sealed {
// Required method
fn is_terminal(&self) -> bool;
}
Trait to determine if a descriptor/handle refers to a terminal/tty.
fn is_terminal(&self) -> bool
Returns true if the descriptor/handle refers to a terminal/tty.
On platforms where Rust does not know how to detect a terminal yet, this will return false. This will also return false if an unexpected error occurred, such as from passing an invalid file descriptor.
On Windows, in addition to detecting consoles, this currently uses some heuristics to detect older msys/cygwin/mingw pseudo-terminals based on device name: devices with names starting with msys- or cygwin- and ending in -pty will be considered terminals. Note that this may change in the future.
An example of a type for which IsTerminal is implemented is Stdin:
use std::io::{self, IsTerminal, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
// Indicate that the user is prompted for input, if this is a terminal.
if stdin.is_terminal() {
print!("> ");
io::stdout().flush()?;
}
let mut name = String::new();
let _ = stdin.read_line(&mut name)?;
println!("Hello {}", name.trim_end());
Ok(())
}The example can be run in two ways:
echo "foo" | path/to/executable it will print: Hello foo.path/to/executable directly, it will prompt for input.impl IsTerminal for File
impl IsTerminal for BorrowedFd<'_>Available on Unix or HermitCore or target_os=trusty or WASI or target_os=motor only.
impl IsTerminal for OwnedFdAvailable on Unix or HermitCore or target_os=trusty or WASI or target_os=motor only.
impl IsTerminal for BorrowedHandle<'_>Available on Windows only.
impl IsTerminal for OwnedHandleAvailable on Windows only.
impl IsTerminal for Stderr
impl IsTerminal for StderrLock<'_>
impl IsTerminal for Stdin
impl IsTerminal for StdinLock<'_>
impl IsTerminal for Stdout
impl IsTerminal for StdoutLock<'_>
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/io/trait.IsTerminal.html