cross-platform coloured text in terminal

Lie Ryan lie.1296 at gmail.com
Fri Apr 16 12:59:49 EDT 2010


On 04/16/10 19:28, Jonathan Hartley wrote:
> I'm playing with ideas of what API to expose. My favourite one is to
> simply embed ANSI codes in the stream to be printed. Then this will
> work as-is on Mac and *nix. To make it work on Windows, printing could
> be done to a file0-like object which wraps stdout:

The problem with that is you're simply reinventing ANSI.SYS device driver.

An alternative API is you could override .__add__(), like so (completely
untested):

class Color(object):
   def __init__(self, color):
       self.color =  map_the_color(color)
       self.string = ""
   def __add__(self, string):
       self.string += string
       return self
   def __str__(self):
       if terminal_can_do_ansi_color:
           return ansicolorescape(self.string, self.color)
       elif windows:
           syscalltocolor(self.color)
           print self.string
           syscalltocolor(reset the color)
           return ""

GREEN = Color('green')
print GREEN + "Great" + "Good"

you can even go a bit further and allow chained calls (again, completely
untested, but you get the idea):

class Color(object):
   def __init__(self, color):
       self.color =  map_the_color(color)
       self.stack = []
   def __add__(self, string):
       if isinstance(string, Color):
           # not a string, chain the calls
           self.stack.append((string.color, []]))
       else:
           # a string,
           self.stack[-1][1].append(string)
       return self
   def __radd__(self, string):
       self.stack.append([self.default, string])
       return self

   def __str__(self):
       if ansi_capable:
           return colorescape(format, string)
       elif windows:
           for format, string in self.stack:
               syscalltocolor(color)
               print string
               return ""

GREEN = Color('green')
RED = Color('red')

print "Fairly" + GREEN + "Great" + RED + "Poor"

or something like that, and you will have an API that works
transparently on all platforms. The downside is that you cannot call
str(GREEN + "foo") on windows.



More information about the Python-list mailing list