Archive

Posts Tagged ‘termcolor’

Print colored text in terminal

March 16, 2011 3 comments

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.");
Categories: python Tags: , , ,
Design a site like this with WordPress.com
Get started