]>
jfr.im git - z_archive/twitter.git/blob - twitter/ansi.py
2 Support for ANSI colours in command-line client.
8 ansi reset colour (ansi value)
10 .. data:: COLOURS_NAMED
11 dict of colour names mapped to their ansi value
13 .. data:: COLOURS_MIDS
14 A list of ansi values for Mid Spectrum Colours
23 COLOURS_NAMED
= dict(list(zip(
24 ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'],
25 [str(x
) for x
in range(30, 38)]
28 colour
for name
, colour
in list(COLOURS_NAMED
.items())
29 if name
not in ('black', 'white')
32 class AnsiColourException(Exception):
33 ''' Exception while processing ansi colours '''
36 class ColourMap(object):
38 Object that allows for mapping strings to ansi colour values.
40 def __init__(self
, colors
=COLOURS_MIDS
):
41 ''' uses the list of ansi `colors` values to initialize the map '''
43 self
._colourIter
= itertools
.cycle(colors
)
45 def colourFor(self
, string
):
47 Returns an ansi colour value given a `string`.
48 The same ansi colour value is always returned for the same string
50 if string
not in self
._cmap
:
51 self
._cmap
[string
] = next(self
._colourIter
)
52 return self
._cmap
[string
]
55 ''' Returns the ansi cmd colour for a RESET '''
56 if sys
.stdout
.isatty():
61 def cmdColour(colour
):
63 Return the ansi cmd colour (i.e. escape sequence)
64 for the ansi `colour` value
66 if sys
.stdout
.isatty():
67 return ESC
+ "[" + colour
+ "m"
71 def cmdColourNamed(colour
):
72 ''' Return the ansi cmdColour for a given named `colour` '''
74 return cmdColour(COLOURS_NAMED
[colour
])
76 raise AnsiColourException('Unknown Colour %s' %(colour))