5 Dec 2011
Printing colors in the terminal
If you fancy adding a bit of color to your console print statements, you can do that by using the ANSI escape sequences. Pasting the following in a Python console (Linux/Mac) will get you some green text!
print "\033[0;32mGREEN TEXT\033[0m"
Although that looks gibberish, the format can be broken down like this:
START_SEQx;y;zmDISPLAY_TEXTEND_SEQ
Starting sequence: \033[
x;y;z: ANSI color codes
Display text: Text you want to display
Ending sequence: \033[0m
You can mix and match x;y;z combinations to get a variety of effects! For example, this will print a blinking green text on red background:
print "\033[5;41;32mGREEN TEXT\033[0m" # oh the horror!
ANSI color codes for your pleasure:
| Text color | Code | Text style | Code | Background color | Code |
|---|---|---|---|---|---|
| Black | 30 | No effect | 0 | Black | 40 |
| Red | 31 | Bold | 1 | Red | 41 |
| Green | 32 | Underline | 4 | Green | 42 |
| Yellow | 33 | Blink | 5 | Yellow | 43 |
| Blue | 34 | Inverse | 7 | Blue | 44 |
| Purple | 35 | Hidden | 8 | Purple | 45 |
| Cyan | 36 | Cyan | 46 | ||
| White | 37 | White | 47 |
Use it wisely. Please don’t pollute the screen.
You can follow me on Twitter right here.