DEV Community

Nelson Figueroa
Nelson Figueroa

Posted on • Originally published at nelson.cloud on

You Can Detect if Code Is Being Run Inside a Terminal

I learned about the sys.stdout.isatty() method in Python which allows you to detect if your code is running in a terminal. For example:

import sys

if sys.stdout.isatty():
    print("This program is running in a terminal!")
else:
    print("This program is running somewhere else, like a CI/CD pipeline")
Enter fullscreen mode Exit fullscreen mode

Running the program outputs the following:

$ python3 tty.py
This program is running in a terminal!
Enter fullscreen mode Exit fullscreen mode

But if we pipe the program into some other tool, like cat, it is no longer running in a terminal and prints the other message:

$ python3 tty.py | cat
This program is running somewhere else, like a CI/CD pipeline
Enter fullscreen mode Exit fullscreen mode

This is why some colorized output from code is not colorized in CI/CD pipelines. The code itself checks if it’s being run in a terminal, and if not, it doesn’t display colors that would result in junk being displayed due to the nature of ANSI escape codes used in colorization. I always thought that it was the CI/CD systems that suppressed color output but that’s not necessarily the case.

This capability is not unique to Python. Other languages support this too.

In JavaScript:

if (process.stdout.isTTY) {
  console.log("This program is running in a terminal!");
} else {
  console.log("This program is running somewhere else, like a CI/CD pipeline");
}
Enter fullscreen mode Exit fullscreen mode

In Ruby:

if $stdout.tty?
  puts "This program is running in a terminal!"
else
  puts "This program is running somewhere else, like a CI/CD pipeline"
end
Enter fullscreen mode Exit fullscreen mode

In Bash:

if [-t 1]; then
  echo "This program is running in a terminal!"
else
  echo "This program is running somewhere else, like a CI/CD pipeline"
fi
Enter fullscreen mode Exit fullscreen mode

Go doesn’t have a built-in method to detect if code is being run inside a terminal, so we need to import the x/term package:

package main

import (
    "fmt"
    "os"

    "golang.org/x/term"
)

func main() {
    if term.IsTerminal(int(os.Stdout.Fd())) {
        fmt.Println("This program is running in a terminal!")
    } else {
        fmt.Println("This program is running somewhere else, like a CI/CD pipeline")
    }
}
Enter fullscreen mode Exit fullscreen mode

Try it yourself!

Top comments (0)