palettes.ansi

Use the colors a terminal names with ANSI escape codes.

Indices 0 to 15 are the ANSI colors in the order the escape codes number them: black, red, green, yellow, blue, magenta, cyan and white, then the bright eight. A 256-color palette adds the xterm 6x6x6 color cube (16 to 231) and 24 greys (232 to 255). The values are xterm’s defaults.

Example

>>> from palettes import get_palette
>>> ansi = get_palette("ansi", length=256, color_depth=16)
>>> ansi[1] == ansi.RED
True
>>> ansi.nearest(0xFF8700)
208
palettes.ansi.ANSI16 = ((0, 'Black'), (13434880, 'Red'), (52480, 'Green'), (13487360, 'Yellow'), (238, 'Blue'), (13435085, 'Magenta'), (52685, 'Cyan'), (15066597, 'White'), (8355711, 'Bright Black'), (16711680, 'Bright Red'), (65280, 'Bright Green'), (16776960, 'Bright Yellow'), (6053119, 'Bright Blue'), (16711935, 'Bright Magenta'), (65535, 'Bright Cyan'), (16777215, 'Bright White'))

The 16 ANSI colors as (0xRRGGBB, name) pairs, in escape-code order.

class palettes.ansi.AnsiPalette(name='ansi', color_depth=16, swapped=False, cached=True, length=256)[source]

Bases: Palette

The 16 or 256 colors of an ANSI terminal.

Named attributes follow the 16 colors: RED, BRIGHT_RED and so on. nearest maps any RGB color to the closest index, which is how a terminal fits a 24-bit color into one palette index.

Parameters:
  • name (str) – Prefix for name (length suffix is added).

  • color_depth (int) – Output format; see Palette.

  • swapped (bool) – Byte-swap 16-bit colors when True.

  • cached (bool) – Memoize index lookups when True (default).

  • length (int) – 16 for the ANSI colors alone, or 256 (default) for the xterm set.

Raises:

ValueError – If length is not 16 or 256.

nearest(r, g=None, b=None)[source]

Return the index of the palette color closest to an RGB color.

A 16-color palette searches all 16. A 256-color palette compares the 16 ANSI colors, the nearest cube color and the nearest grey.

Parameters:
  • r (int) – Red (0–255), a 24-bit 0xRRGGBB integer, or an (r, g, b) sequence.

  • g (int) – Green when r is passed separately.

  • b (int) – Blue when r is passed separately.

Returns:

int – A palette index.