An efficient and simple ANSI colors module (and also a powerful script), with functions to print text using colors. https://bitbucket.org/lbesson/ansicolortags.py
The names of the colors follow these conventions:
- for the eight ANSI colors (black, red, green, yellow, blue, magenta, cyan, white):
- the name in minuscule is for color with bold (example ‘yellow‘),
- the name starting with ‘B’ is for color without bold (example ‘Byellow‘),
- the name starting with a capital letter is for the background color (example ‘Yellow‘).
- for the special effects (underline, negative), they might not always be supported, but they usually are:
, italic, bold,
- the name in minuscule is used to turn on the effect (example ‘i’ to turn on italic),
- the name starting in capital letter is used to turn down the effect (example ‘I’ to turn off italic).
- for the other special effects (
el), the effect is immediate (and seems to be well supported).
List of functions¶
To print a string¶
To clean the terminal or the line¶
Example of use (module)¶
To store a string, use
sprint() (i.e. print to a string, sprint), like this:
>>> example = sprint("France flag is <blue>blue<white>white<red>red<white>, Italy flag have <green>green on it<white>.") >>> example 'France flag is [01;34mblue[01;37mwhite[01;31mred[01;37m, Italy flag have [01;32mgreen on it[01;37m.'
example can then be printed, with colors, with:
>>> print(example) # Sorry, but in the documentation it is hard to show colors :) France flag is bluewhitered, Italy flag have green on it.
To directly print a string colored by tags, use
printc() (colors will be there if you try this in your terminal):
>>> printc("<reset><white>Batman's costum is <black>black<white>, Aquaman's costum is <blue>blue<white> and <green>green<white>.<reset>") Batman's costum is black, Aquaman's costume is blue and green.
This is the most useful function. To do the same, but on any file, use
Moreover, the function
erase() can also be useful to simply delete all valid color tags:
>>> print(erase("<reset>Batman's costum is <black>black<white>, Aquaman's costum is <blue>blue<white> and <green>green<white>, and this is a non-valid <tag>, so it is kept like this.<reset>")) Batman's costum is black, Aquaman's costum is blue and green, and this is a non-valid <tag>, so it is kept like this
In this last example, an
<el> tag (
el) is used to erase the current content of the line, useful to make a dynamical print:
>>> writec("<reset><red>Computing <u>len(str(2**562017))<reset>...."); tmp = len(str(2**562017)); writec("<el><green>Done !<reset>") Done !
The first part of the line ‘Computing len(str(2**562017))....’ have disappeared after the computation! (which takes about one second).
Example of use (script)¶
- To show the help
$ ansicolortags.py --help;
- To run a test
$ ansicolortags.py --test;
- To produce a GNU Bash color aliases file
$ ansicolortags.py --generate --file ~/.color_aliases.sh.
This script can normally detect if ANSI codes are supported :
$ ansicolortags.py --help: will print with colors if colors seems to be supported;
$ ansicolortags.py --help --noANSI: will print without any colors, even if it is possible;
$ ansicolortags.py --help --ANSI: will force the use of colors, even if they seems to be not supported.
And, the module part behaves exactly like the script part.
This project can be found on-line:
- here on BitBucket: https://bitbucket.org/lbesson/ansicolortags.py
- here on PyPi: https://pypi.python.org/pypi/ansicolortags
And some documentation on ANSI codes:
© Lilian Besson, 2012-2017.
Reset() → unit¶
Try to reset the current ANSI codes buffer, using
_generate_color_sh(file_name=None) → string | unit.¶
Used to print or generate (if file_name is present and is a valid URI address) a profile of all the colors defined in this file.
Print all ANSI Colors as
export NAME="VALUE". Useful to automatically generate a
.color.shfile, to be used with Bash: and now you can easily colorized your Bash script with
. color.shto import all colors.
The file is a list of
export NAME="VALUE", to be used with GNU Bash.
For example, to generate the
color.shfile with this script, use the
$ python -m ansicolortags -g -f color.sh
I suggest to save this
.color.shfile to your home, like
~/.color.sh, so it will be available for any GNU Bash script. During the last 4 years, all the Bash scripts I wrote that uses this color profile (or assume it to be enabled, e.g. from your .bashrc file) assume it to be saved as
In a Bash script, I suggest to source this
.color.shfile like this (it checks if the file exists before sourcing it):
[ -f ~/.color.sh ] && . ~/.color.sh
_run_complete_tests() → unit.¶
Launch a complete test of all ANSI Colors code in the list
clearLine() → unit¶
Try to clear the current line using ANSI code
clearScreen() → unit¶
Try to clear the screen using ANSI code
erase(chainWithTags, left='<', right='>', verbose=False) → string¶
Parse a string containing color tags, when color is one of the previous define name, and then return it, with color tags erased.
>>> print(erase("<reset><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> !
This example seems exactly the same that the previous one in the documentation, but it’s not (it is impossible to put color in the output of a Python example in Sphinx documentation, so there is no color in output in the examples... but be sure there is the real output !).
This function can mess up a string which has unmatched opening and closing tags (
<), use it carefully.
notify(msg='', obj='Notification sent by ansicolortags.notify', icon=None, verb=False) → bool¶
notify-send(GNU/Linux command-line program). Also print the informations directly to the screen (only if verb=True).
This does not use any ANSI escape codes, but the common notify-send GNU/Linux command line program. It will probably fail (but cleanly) on Windows or Mac OS X.
- Return True if and only if the title have been correctly changed.
- Fails simply if
notify-sendis not found.
printc(chainWithTags, *objects, left='<', right='>', sep=' ', end='n', erase=False, **kwargs) → unit¶
Basically a shortcut to
print(sprint(chainWithTags)): it analyzes all tags (i.e., it converts the tags like
<red>to their ANSI code value, like
red), and then it prints the result.
Example (in a terminal the colors, and the bold and underlining effects would be there):
>>> printc("<reset><white>« <u>Fifty shades of <red>red<white><U> » could be a <green>good<white> book, <b>if it existed<B>.<reset>") « Fifty shades of red » could be a good book, if it existed.
It accepts one or more “things” to print, exactly like
print(): for each value
arg_iis a string, it is converted using
sprint(arg_i, left=left, right=right)(
sprint()), and then passed to
arg_iis passed to
print()without modification (in the same order, of course).
Example with more than one object:
>>> print("OK n =", 17, "and z =", 1 + 5j, ".") OK n = 17 and z = (1+5j) . >>> printc("<reset><green>OK<white> n =<magenta>", 17, "<white>and z =<blue>", 1 + 5j, "<reset>.") # in a terminal, the output will have colors: OK n = 17 and z = (1+5j) .
This is the more useful function in this package.
I suggest to use ansicolortags.py in your own project with the following piece of code:
try: from ansicolortags import printc except ImportError: print("WARNING: ansicolortags was not found, disabling colors instead.\nPlease install it with 'pip install ansicolortags'") def printc(*a, **kwargs): print(*a, **kwargs)
sprint(chainWithTags, left='<', right='>', verbose=False) → string¶
Parse a string containing color tags, when color is one of the previous define name, and then return it, with color tags changed to concrete ANSI color codes.
Tags are delimited by
right. By default, it’s HTML / Pango style whit ‘<’ and ‘>’, but you can change them.
For example, a custom style even closer to HTML could be:
right = '</span>'is also possible.
It is more prudent to put nothing else than ANSI Colors (i.e. values in
chainWithTags. The behavior of the function in case of false tags is not perfect. Moreover, a good idea could be to try not to use ‘<’ or ‘>’ for anything else than tags. I know, it’s not perfect. But, the syntax of color tags is so simple and so beautiful with this limitation that you will surely forgive me this, won’t you ;) ?
Example (where unknown tags are left unmodified, and the colors should be there):
>>> print(sprint("<reset><blue>This is blue.<white> And <this> is white.<red> Now this is red because I am <angry> !<green><reset>")) This is blue. And <this> is white. Now this is red because I am <angry> !
This function is used in all the following, so all other function can also use
tocolor(mystring) → string¶
Convert a string to a color.
mystringhave to be in
colorDictto be recognized (and interpreted). Default value if
mystringis not one of the color name is
""the empty string.
writec(chainWithTags="", out=sys.stdout, left='<', right='>', flush=True) → unit¶
Useful to print colored text to a file, represented by the object
out. Also useful to print colored text, but without any trailing ‘n’ character.
In this example, before the long computation begin, it prints ‘Computing 2**(2**(2**4)).....’, and when the computation is done, erases the current line (with
el), and prints ‘ 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>") Done !
This example show how to use this module to write colored data in a file. Be aware that this file now contains ANSI escape sequences. For example,
$ cat /tmp/colored-text.txtwill well print the colors, but editing the file will show hard values of escape code:
>>> my_file = open('/tmp/colored-text.txt', mode = 'w') # Open an random file. >>> write("<reset><blue>this is blue.<white>And <this> is white.<red>Now this is red because I am <angry> !<green><reset>", file = my_file) >>> # Now this file '/tmp/colored-text.txt' has some ANSI colored text in it.
Remark: It can also be used to simply reinitialize the ANSI colors buffer, but the function
Reset()is here for this:
outwill be flushed by this function if
flushis set to
True(this is default behavior). If you prefer no to, use
>>> writec(chainWithTags_1, out=my_file, flush=False) >>> # many things... >>> writec(chainWithTags_n, out=my_file, flush=False) >>> my_file.flush() # only flush here!
xtitle(new_title="", verb=False) → 0 or 1¶
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 calling the
xtitleprogram does not work (or if it is not installed).
The second solution simply uses the two ANSI Tags
bell). So, you can also do it with:
>>> ansicolortags.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.