ANSIColors Module

An efficient and simple ANSI colours module (and also a powerfull script), with functions to print text using colours.

About the convention for the names of the colours :
  • for the eight colours black, red, green, yellow, blue, magenta, cyan, white:
  • the name in minuscule is for colour with bold (example ‘yellow’),
  • the name starting with ‘B’ is for colour without bold (example ‘Byellow’),
  • the name starting with a capital letter is for the background colour (example ‘Yellow’).
  • for the special effects (blink, italic, bold, underline, negative), not always supported :
  • the name in minuscule is for activate the effect,
  • the name starting in capital letter is for desactivate the effect.
  • for the other special effects (nocolours, default, Default, clear, el), the effect is immediate (and seems to be well supported).

List of functions:

To print a string

  • sprint: give a string,
  • printc: like __builtin__.print, but with interpreting balises to put colours,
  • writec: like printc, but using any file object (and no new line added at the end of the string),

To clean the terminal or the line

  • erase: erase all ANSI colours balises in the string (like sprint, but erasing and not interpreting colour balises)
  • clearLine, clearScreen: to clear the current line or screen,
  • Reset: to return to default foreground and background, and stopping all fancy effects (like blinking or reverse video).

Others functions

  • notify: try to display a system notification. Only on *linux*.
  • xtitle: try to set the title of the terminal. Not always supported.

Example of use (module) :

To store a string, use sprint (i.e. print to a string, sprint), like here

>>> example=sprint("France flag is <blue>blue<white>white<red>red<white>, Italy flag have <green>green on it<white>.")

The string example can then be printed, with colours, with

>>> print example # Sorry, but in the documentation it is hard to show colours :)
France flag is bluewhitered, Italy flag have green on it.

To directly print a string colored by balises, use printc

>>> printc("Batman's costum is <black>black<white>, Aquaman's costum is <blue>blue<white> and <green>green<white>.")

See also

This is the most usefull function. To do the same, but on any file, use writec

Moreover, the function erase can also be usefull to simply delete all valid colour balises

>>> print erase("Batman's costum is <black>black<white>, Aquaman's costum is <blue>blue<white> and <green>green<white>, and this is a non-valid <balise>, so it is kept like this.")
Batman's costum is black, Aquaman's costum is blue and green, and this is a non-valid <balise>, so it is kept like this

In this last example, <el> balise is used to erase the current content of the line, usefull to make a dynamical print

>>> writec("<red>Computing <u>2**(2**(2**4))<reset>...."); tmp=2**(2**(2**4)); writec("<el><green> Done !<reset>")
Done !

The first ‘Computing 2**(2**(2**4))....’ have disappeared after the computation !

Example of use (script):

  • To show the help $ ANSIColors.py --help;
  • To run a test $ ANSIColors.py --test;
  • To produce a GNU Bash colour aliases file $ ANSIColors.py --generate --file ~/.colour_aliases.sh

Auto detection

Now, this script can detect if ANSI codes are supported :
  1. $ ANSIColors.py --help : will print with colours if colours seems to be supported;
  2. $ ANSIColors.py --help --noANSI : will print without any colours, even if it is possible;
  3. $ ANSIColors.py --help --ANSI : will force the use of colours, even they seems to be not supported.

And, the module part behaves exactly like the script part.

This functionality is still experimental, and work only on Ubuntu 11.10, as far as I know.


About:

This module is still in development. Last version of this project can be found on-line :

The reference page for ANSI code is : here on Wikipedia. The reference page for XTitle escape code is : here.

Documentation

The doc is available on-line :

Or some explanations (and an OCaml version of this module) are available on my Google Site tools/ansi-colors.

Copyrigths:

(c) October 2012 - Mars 2013 By Lilian BESSON, ENS de Cachan (M1 Mathematics & M1 Computer Science MPRI) mailto:lbesson@ens-cachan.fr

For Naereen Corp. mailto:naereen-corporation@laposte.net https://sites.google.com/site/naereencorp/tools/ansicolors

ANSIColors.ANSISupported = True

If false, the module do almost NOTHING

ANSIColors.black = '\x1b[01;30m'

Black and bold.

ANSIColors.red = '\x1b[01;31m'

Red and bold.

ANSIColors.green = '\x1b[01;32m'

Green and bold.

ANSIColors.yellow = '\x1b[01;33m'

Yellow and bold.

ANSIColors.blue = '\x1b[01;34m'

Blue and bold.

ANSIColors.magenta = '\x1b[01;35m'

Magenta and bold.

ANSIColors.cyan = '\x1b[01;36m'

Cyan and bold.

ANSIColors.white = '\x1b[01;37m'

White and bold.

ANSIColors.Bblack = '\x1b[02;30m'

Black and not bold.

ANSIColors.Bred = '\x1b[02;31m'

Red and not bold.

ANSIColors.Bgreen = '\x1b[02;32m'

Green and not bold.

ANSIColors.Byellow = '\x1b[02;33m'

Yellow and not bold.

ANSIColors.Bblue = '\x1b[02;34m'

Blue and not bold.

ANSIColors.Bmagenta = '\x1b[02;35m'

Magenta and not bold.

ANSIColors.Bcyan = '\x1b[02;36m'

Cyan and not bold.

ANSIColors.Bwhite = '\x1b[02;37m'

White and not bold.

ANSIColors.Black = '\x1b[40m'

Black background

ANSIColors.Red = '\x1b[41m'

Red background

ANSIColors.Green = '\x1b[42m'

Green background

ANSIColors.Yellow = '\x1b[43m'

Yellow background

ANSIColors.Blue = '\x1b[44m'

Blue background

ANSIColors.Magenta = '\x1b[45m'

Magenta background

ANSIColors.Cyan = '\x1b[46m'

Cyan background

ANSIColors.White = '\x1b[47m'

White background

Make the text blink. NOT SUPPORTED BY ALL TERMINAL. On Windows (with mintty) it’s ok. On Linux (with ttys, gnome-terminal or pyterminal, it’s not).

Make the text not blink (i.e. stop blinking).

ANSIColors.default = '\x1b[39m'

default foreground

ANSIColors.Default = '\x1b[49m'

default background

ANSIColors.italic = '\x1b[3m'

italic

ANSIColors.Italic = '\x1b[23m'

no italic

ANSIColors.b = '\x1b[1m'

bold

ANSIColors.B = '\x1b[2m'

no bold

ANSIColors.u = '\x1b[4m'

underline

ANSIColors.U = '\x1b[24m'

no underline

ANSIColors.neg = '\x1b[7m'

negative

ANSIColors.Neg = '\x1b[27m'

no negative

ANSIColors.clear = '\x1b[2J'

Clear the screen.

ANSIColors.el = '\r\x1b[K'

Clear the current line.

ANSIColors.reset = '\x1b[0;39;49m'

Reset the current foreground and background values to default, and disable all effects.

ANSIColors.bell = '\x07'

BEL is the bell character (007). It might be interpreted and a sonor signal might be heard (but not with every terminals).

ANSIColors.title = '\x1b]0;'

Use it like : writec(“<title>.: My title :.<bell>”), and only with ending the sequence with <bell>.

ANSIColors.warning = '\x1b[01;31m\x1b[4m/!\\\x1b[24m\x1b[39m'

A well colored Warning symbol (/!\)

ANSIColors.question = '\x1b[01;33m\x1b[4m/?\\\x1b[24m\x1b[39m'

A well colored question symbol (/?\)

ANSIColors.ERROR = '\x1b[0;39;49m\x1b[01;31mERROR\x1b[39m'

A well colored ERROR word.

ANSIColors.WARNING = '\x1b[0;39;49m\x1b[01;33mWARNING\x1b[39m'

A well colored WARNING word.

ANSIColors.INFO = '\x1b[0;39;49m\x1b[01;34mINFO\x1b[39m'

A well colored INFO word.

ANSIColors.colorList = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'Bblack', 'Bred', 'Bgreen', 'Byellow', 'Bblue', 'Bmagenta', 'Bcyan', 'Bwhite', 'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White', 'Blink', 'blink', 'nocolors', 'default', 'Default', 'italic', 'Italic', 'b', 'B', 'u', 'U', 'neg', 'Neg', 'clear', 'el', 'reset', 'bell', 'title', 'warning', 'question', 'ERROR', 'WARNING', 'INFO']

List of all authorized colours.

ANSIColors.simpleColorList = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']

List of all simple colours

ANSIColors.tocolor(string) → string[source]

Convert a string to a colour. [string] have to be in [colorList] to be recognized (and interpreted). Default value if [string] is not one of the colour name is “” the empty string.

ANSIColors.sprint(chainWithBalises, left='<', right='>', verbose=False) → string[source]

Parse a string containing colour balises, when colour is one of the previous define name, and then return it, with colour balises changed to concrete ANSI colour codes.

Balises are delimited by [left] and [right]. By default, it’s Pango style whit ‘<’ and ‘>’, but you can change them. For example, a HTML style like : left=’<span colour=’ and right=’>’ is also possible. (But, without closing ‘</span’, this is a stupid example. Sorry I didn’t find anything else...)

Warning

It is more prudent to put nothing else than ANSI Colors (i.e. values in colorList) between ‘<’ and ‘>’ in [chainWithBalises]. The comportement of the function in case of false balises is not perfect. Moreover, a good idea could be to don’t try to use ‘<’ or ‘>’ for anything else than balises. I know, it’s not perfect. But, the syntax of color balises is so simple and se beautiful with this limitation that you will surely forgive me this, won’t you ;) ?

Example:

>>> print sprint("<blue>this is blue.<white>And <this> is white.<red>Now this is red because I am <angry> !<green><white>")
this is blue.And <this> is white.Now this is red because I am <angry> !
About:
This function is used in all the following, so all other function can also used left and right arguments.
ANSIColors.erase(chainWithBalises, left='<', right='>', verbose=False) → string[source]

Parse a string containing colour balises, when colour is one of the previous define name, and then return it, with colour balises erased.

Example:
This example seems exactly the same that the previous in the documentation, but it’s not (again: it is hard and painful (and maybe impossible) to put colour in Sphinx RST files, so there is no colour in output in the examples... but be sure there is the real output !).
>>> print erase("<blue>This is blue.<white>And <this> is white.<red>Now this is red because I am <angry> !<reset>")
This is blue.And <this> is white.Now this is red because I am <angry> !
ANSIColors.printc(chainWithBalises, left='<', right='>') → unit[source]

A shortcut to print sprint(chainWithBalises) : analyse all balises, and print the result.

ANSIColors.writec(chainWithBalises="", file=sys.stdout, left='<', right='>', flush=True) → unit[source]

Usefud to print colored text to a file, represented by the object file. Also usefull to print colored text, but without an ending ‘n’ caracter.

Example:

In this example, before the long calcul begin, it print ‘Computing 2**(2**(2**4)).....’, and when the computation is done, erase the current line (with <el> balise), and print ‘ Done !’ in green, and the result of the computation:

>>> writec("<red>Computing<reset> 2**(2**(2**4))....."); tmp=2**(2**(2**4)); writec("<el><green>Done !<reset>")

This example show how to use ANSIColors module to put colored data in a file. Be aware that this file now contains ANSI escape sequences. For example, $ cat /tmp/colored-text.txt * will well print the colours, but editing the file will show *hard values of escape code (you know, the stuff that you typically don’t want to know anything, the **dirty stuff* !*):

>>> my_file = open('/tmp/colored-text.txt', mode='w') # Open an adhoc file.
>>> write("<blue>this is blue.<white>And <this> is white.<red>Now this is red because I am <angry> !<green><white>", file=my_file)
Remark:

Can also be used to simply reinitialize the ANSI colors buffer, but the function Reset is here for this:

>>> writec("<reset>")

Warning

The file file will be flushed by this function if flush is set to True (this is default comportement). If you prefer no to, use flush=False option:

>>> writec(chainWithBalises_1), file=my_file, flush=False)
>>> # many things.
>>> writec(chainWithBalises_n), file=my_file, flush=False)
>>> my_file.flush()      # only flush *here*.
ANSIColors.clearScreen() → unit[source]

Try to clear the screen using ANSI code [clear].

ANSIColors.clearLine() → unit[source]

Try to clear the current line using ANSI code [el].

ANSIColors.Reset() → unit[source]

Try to reset the current ANSI codes buffer, using [reset].

ANSIColors.notify(msg='', obj='.: Notification sent by ANSIColors.notify :.', icon=None, verb=False) → bool[source]

Notification using subprocess and notify-send. Also print the informations directly to the screen (only if verb=True).

Warning

This doesn’t use any ANSI escape codes, but the common notify-send linux program. It shall fails (but not durty) on Windows or Mac OS X.

Return True iff the title have been correctly changed. Fails simply if notify-send is not found.

ANSIColors.xtitle(new_title="", verb=False) → 0|1[source]

Modify the current terminal title. Returns 0 if one of the two solutions worked, 1 otherwise.

An experimental try is with ANSI escape code, if the simple way by invoking the xtitle program doesn’t work (or if it is not installed).

Note

The second solution used the two ANSI Balises <title> and <bell>. So, you can also do it with :

>>> ANSIColors.writec("<title>.: This is the new title of the terminal :.<bell>")

But this function xtitle is better : it tries two ways, and returns a signal to inform about his success.