Mimsy Were the Borogoves

Hacks: Articles about programming in Python, Perl, Swift, BASIC, and whatever else I happen to feel like hacking at.

Using Term::ANSIColor with GeekTool

Jerry Stratton, February 10, 2011

I was looking for something else this morning and ran across Term::ANSIColor. Instead of having to look up the color codes in a table and output them exactly right, Term::ANSIColor makes manipulating ANSI codes much easier—and thus less likely to error.

There may be some cases where I don’t want to introduce any dependencies or overhead, but for the most part, Term::ANSIColor should be a much better choice.

In each of the two scripts, it’s just a matter of replacing the variables. Instead of:

  • $critical="\e[31m"; #red
  • $warning="\e[35m"; #magenta
  • $notice="\e[33m"; #yellow
  • $clear="\e[0m";

Import Term::ANSIColor:

  • use Term::ANSIColor;
  • $critical = color 'red on_black';
  • $warning = color 'magenta on_black';
  • $notice = color 'yellow on_black';
  • $clear = color 'reset';

Everything else remains the same.

And for the vm_stat script:

  • use Term::ANSIColor;
  • $okay = color 'green';
  • $critical = color 'red';
  • $problem = color 'yellow';
  • $clear = color 'reset';

One odd issue I ran into is that GeekTool appears to need the ‘reset’ to be followed by a carriage return. Running this Whammy Burger script directly on the command line will act normally—print the text in green—but running it in GeekTool will display an “[0m” at the end of the green text.

  • #!/usr/bin/perl
  • use Term::ANSIColor;
  • print color 'green';
  • print "Whammy Burger!\n";
  • print color 'reset';

The solution is to move the final ‘\n’ below the reset.

In response to GeekTool, Perl, and ANSI color codes: GeekTool is a great way to display the results of little scripts on your desktop. Using ANSI color codes can make those scripts even more useful. You can also change the status of the status button from “success” to “failure” depending on your script’s exit code.