Getting correct string length in Python for strings with ANSI color codes

The pyparsing wiki includes this helpful expression for matching on ANSI escape sequences: ESC = Literal(‘\x1b’) integer = Word(nums) escapeSeq = Combine(ESC + ‘[‘ + Optional(delimitedList(integer,’;’)) + oneOf(list(alphas))) Here’s how to make this into an escape-sequence-stripper: from pyparsing import * ESC = Literal(‘\x1b’) integer = Word(nums) escapeSeq = Combine(ESC + ‘[‘ + Optional(delimitedList(integer,’;’)) + oneOf(list(alphas))) … Read more

How do I print colored text to the terminal?

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here’s some Python code from the Blender build scripts: class bcolors: HEADER = ‘\033[95m’ OKBLUE = ‘\033[94m’ OKCYAN = ‘\033[96m’ OKGREEN = ‘\033[92m’ WARNING = ‘\033[93m’ FAIL = ‘\033[91m’ … Read more