I work in the terminal a lot and I often want to write programs that color their output a bit. For example, perhaps I'm looking at a sequencing read and I want to know what part of it was the reason it was flagged. I could use colorama, termcolor, or another library, but including a dependency for something this simple is not really worth it. Instead, printing colored text is as simple as:

COLOR_RED_BOLD = '\x1b[1;31m'
COLOR_BLUE_BOLD = '\x1b[1;34m'
COLOR_END = '\x1b[0m'
print(
  "One fish, two fish, " +
  COLOR_RED_BOLD + "red" +
  COLOR_END + " fish, " +
  COLOR_BLUE_BOLD + "blue" +
  COLOR_END + " fish.")

I usually just want one or two highlight colors, typically in bold, and rarely find the six standard colors limiting. It's especially helpful if you want to draw your eye to something specific, while maintaining the context around it when you need to look further.

How compatible is this? Will someone with a non-ANSI terminal someday run my code and complain? One data point is that I wrote icdiff with this approach in 2009, and it's been reasonably popular. While I've gotten hundreds of bug reports this has never been one people have complained about.

Comment via: facebook, mastodon

New Comment
1 comment, sorted by Click to highlight new comments since: Today at 5:02 AM

It's unlikely that anyone will complain when they run on a non-ANSI terminal.  It's ugly to hardcode, and there certainly exist terminals today that won't be compatible, but not many who cant find a compatible option when needed.  If you really care (or if this is for professional code that others will have to maintain in the future, or if you get into more interesting terminal manipulations like full-screen addressing or ...), it's worth taking a dependency on ncurses, which can both test for capabilities and abstract away most of them for very VERY broad compatibility.

ANSI escape sequences have been common since the early '80s, but only this millennium has it been universal enough to trust it and not try to support anything else.

BTW, I've found it to be worth setting up https://ethanschoonover.com/solarized/ for my editors and various terminal software I use.  Much easier on the eyes than the standard 16-color palette, and reasonably compatible in terms of contrasts.