It depends on what you want. ANSI colors technically refers to the 8-color palette implied by ECMA-48 (ISO-6429) which has named constants in curses. Libraries don't store escape sequences; those are in a database. For an ANSI (sic) terminal, those correspond to escape sequences which set graphic rendition (video attributes such as bold, underline, reverse — and color).
termcap, terminfo and curses use a more general notion where you start with a color number and generate the escape sequence which can produce the corresponding color. Terminals can have no colors, multiple colors (8 for instance, but possibly 16, 88, 256 for xterm and similar terminals). The information telling how to do this is stored in the terminal database as named capabilities. To set the ANSI foreground color, you would use setaf
, either using a library call or a command-line application such as tput
, e.g.,
tput setaf 4
for color 4 (blue). Simple applications use the low-level termcap or terminfo interfaces, usually with terminfo databases. While you might be inclined to format your own escape sequences, theses interfaces provide formatting functions that let you avoid knowing how many colors a terminal might support. The terminal database tells your program, using the TERM
environment variable to select the actual terminal description. If you have a terminal supporting more than 8 colors, the escape sequence is not formed by adding 30 or 40 to the color number.
Here is an example using the low-level terminfo interface from Python:
import curses
curses.setupterm()
curses.putp(curses.tparm(curses.tigetstr("setaf"), curses.COLOR_RED))
curses.putp(curses.tparm(curses.tigetstr("setab"), curses.COLOR_YELLOW))
curses.putp("hello!")
curses.putp(curses.tigetstr("sgr0"))
curses.putp("\n")
Further reading: