You Can Detect If Code Is Being Run Inside a Terminal

speckx1 pts0 comments

You Can Detect if Code Is Being Run Inside a Terminal | Nelson FigueroaI learned about the sys.stdout.isatty() method in Python which allows you to detect if your code is running in a terminal. For example:<br>Pythonimport sys

if sys.stdout.isatty():<br>print("This program is running in a terminal!")<br>else:<br>print("This program is running somewhere else, like a CI/CD pipeline")<br>Running the program outputs the following:<br>Console$ python3 tty.py<br>This program is running in a terminal!

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:<br>Console$ python3 tty.py | cat<br>This program is running somewhere else, like a CI/CD pipeline

This is why some colorized output from code is not colorized in CI/CD pipelines. The code itself checks if it&rsquo;s being run in a terminal, and if not, it doesn&rsquo;t display colors that would result in junk being displayed due to the nature of<br>ANSI escape codes used in colorization. I always thought that it was the CI/CD systems that suppressed color output but that&rsquo;s not necessarily the case.<br>This capability is not unique to Python. Other languages support this too.<br>In JavaScript:<br>JavaScriptif (process.stdout.isTTY) {<br>console.log("This program is running in a terminal!");<br>} else {<br>console.log("This program is running somewhere else, like a CI/CD pipeline");<br>In Ruby:<br>Rubyif $stdout.tty?<br>puts "This program is running in a terminal!"<br>else<br>puts "This program is running somewhere else, like a CI/CD pipeline"<br>end<br>In Bash:<br>Shellif [ -t 1 ]; then<br>echo "This program is running in a terminal!"<br>else<br>echo "This program is running somewhere else, like a CI/CD pipeline"<br>fi<br>Go doesn&rsquo;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:<br>Gopackage main

import (<br>"fmt"<br>"os"

"golang.org/x/term"

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

Random Post

Related Posts<br>Creating High Quality GIFs from Asciinema RecordingsUse `agg` with a huge font size to get high quality GIFs.

Quick Tip: Mute the Terminal Login Message with a .hushlogin FileCreate a .hushlogin file in your home directory to silence login messages.

How to Clone a Specific Git Branch Without Other BranchesClone a single Git branch using --single-branch and --depth for faster cloning.

running program terminal else like code

Related Articles