Print colored text in terminal
Problem
In the terminal, you want to print some texts in colored mode. For instance, warnings in red.
Solution
There is a module for this task called termcolor. You can install it with this command:
sudo pip install termcolor
Or, simply download it and put termcolor.py next to your script.
Usage
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
The tip and the example are from this thread.
Update (20110518)
If you want to print something in red (warning/error) or green (OK), here is a simplified solution:
colorred = "\033[01;31m{0}\033[00m"
colorgrn = "\033[1;36m{0}\033[00m"
print colorred.format("Warning! Reactor meltdown. Evacuate immediately!")
print colorgrn.format("Ha-ha, just kidding!")
Same thing in Java:
String colorred = "\033[01;31m%s\033[00m\n"; System.out.printf(colorred, "# Warning! Approaching light speed. Fasten your seatbelts.");

Hi,
Thanks for your post, I’m however having trouble installing the module. Everything seems to go wel in terminal, but python idle tells me module is not found when i try to import it. Do you have an idea of what it can be? Thanks!
users-air:termcolor-1.1.0 User$ sudo python setup.py install
Password:
running install
running build
running build_py
running install_lib
copying build/lib/termcolor.py -> /Library/Python/2.7/site-packages
byte-compiling /Library/Python/2.7/site-packages/termcolor.py to termcolor.pyc
running install_egg_info
Writing /Library/Python/2.7/site-packages/termcolor-1.1.0-py2.7.egg-info
Hi,
Thanks for your post, I’m however having trouble installing the module im trying to get. Everything seems to go wel in terminal, but python idle tells me module is not found when i try to import it. Do you have an idea of what it can be?
users-air:termcolor-1.1.0 User$ sudo python setup.py install
Password:
running install
running build
running build_py
running install_lib
copying build/lib/termcolor.py -> /Library/Python/2.7/site-packages
byte-compiling /Library/Python/2.7/site-packages/termcolor.py to termcolor.pyc
running install_egg_info
Writing /Library/Python/2.7/site-packages/termcolor-1.1.0-py2.7.egg-info
Try to import it. I don’t use idle, but in the shell it looks like this:
If you get the prompt back, then there was no error, the import was successful. Then do the same in idle.