]>
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
]
54 class AnsiCmd(object):
55 def __init__(self
, forceAnsi
):
56 self
.forceAnsi
= forceAnsi
59 ''' Returns the ansi cmd colour for a RESET '''
60 if sys
.stdout
.isatty() or self
.forceAnsi
:
65 def cmdColour(self
, colour
):
67 Return the ansi cmd colour (i.e. escape sequence)
68 for the ansi `colour` value
70 if sys
.stdout
.isatty() or self
.forceAnsi
:
71 return ESC
+ "[" + colour
+ "m"
75 def cmdColourNamed(self
, colour
):
76 ''' Return the ansi cmdColour for a given named `colour` '''
78 return self
.cmdColour(COLOURS_NAMED
[colour
])
80 raise AnsiColourException('Unknown Colour %s' % (colour
))
83 if sys
.stdout
.isatty() or self
.forceAnsi
:
88 def cmdUnderline(self
):
89 if sys
.stdout
.isatty() or self
.forceAnsi
:
94 """These exist to maintain compatibility with users of version<=1.9.0"""
96 return AnsiCmd(False).cmdReset()
98 def cmdColour(colour
):
99 return AnsiCmd(False).cmdColour(colour
)
101 def cmdColourNamed(colour
):
102 return AnsiCmd(False).cmdColourNamed(colour
)