How to Print Colored Text to the Terminal

How do I print colored output to the terminal in Python?

Would the Python termcolor module do? This would be a rough equivalent for some uses.

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

The example is right from this post, which has a lot more. Here is a part of the example from docs

import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way. While I stated in the original post that this is possible with this module I now don't think so. See the last section for a way to do that.

However, most of the time we print short segments of text in color, a line or two. So the interface in these examples may be a better fit than to 'turn on' a color, print, and then turn it off. (Like in the Perl example shown.) Perhaphs you can add optional argument(s) to your print function for coloring the output as well, and in the function use module's functions to color the text. This also makes it easier to resolve occasional conflicts between formatting and coloring. Just a thought.


Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode.

Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way. Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC[ followed by the codes for "bright" attribute (1) and red color (31), followed by m

# print "\033[1;31m"   # this would emit a new line as well
import sys
sys.stdout.write("\033[1;31m")
print "All following prints will be red ..."

To turn off any previously set attributes use 0 for attribute, \033[0;35m (magenta).

To suppress a new line in python 3 use print('...', end=""). The rest of the job is about packaging this for modular use (and for easier digestion).

File colors.py

RED   = "\033[1;31m"  
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"

I recommend a quick read through some references on codes. Colors and attributes can be combined and one can put together a nice list in this package. A script

import sys
from colors import *

sys.stdout.write(RED)
print "All following prints rendered in red, until changed"

sys.stdout.write(REVERSE + CYAN)
print "From now on change to cyan, in reverse mode"
print "NOTE: 'CYAN + REVERSE' wouldn't work"

sys.stdout.write(RESET)
print "'REVERSE' and similar modes need be reset explicitly"
print "For color alone this is not needed; just change to new color"
print "All normal prints after 'RESET' above."

If the constant use of sys.stdout.write() is a bother it can be be wrapped in a tiny function, or the package turned into a class with methods that set terminal behavior (print ANSI codes).

Some of the above is more of a suggestion to look it up, like combining reverse mode and color. (This is available in the Perl module used in the question, and is also sensitive to order and similar.)


A convenient list of escape codes is surprisingly hard to find, while there are many references on terminal behavior and how to control it. The Wiki page on ANSI escape codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information. Here is another page with straight tables of codes.
There is much more out there.

This can be used alongside a module like termocolor.

How do I print colored text to the terminal in Rust?

Rust doesn't have octal escape sequences. You have to use hexadecimal:

println!("\x1b[93mError\x1b[0m");

See also https://github.com/rust-lang/rust/issues/30491.

Edit: What happens, and the reason the compiler does not complain, is that \0 is a valid escape sequence in Rust - and represents the NULL character (ASCII code 0). It is just that Rust, unlike C (and Python), does not allow you to specify octal number after that. So it considers the 33 to be normal characters to print.

How to use ANSI color codes to print colored text to bash terminal from a file?

How would I read a file, color its contents and then print to the terminal?

You could leave the expansions in the file and replace the ${...} forms with the variables when reading the file:

RED=$'\E[0;31m'
NC=$'\E[0m'
GREEN=$'\E[0;32m'
sed 's/No/${RED}No${NC}/g ; s/Yes/${GREEN}Yes${NC}/g' file.txt > color_file.txt
( export RED NC GREEN ; envsubst color_file.txt )

But I believe you wanted to actually output the escape sequences into the file:

RED=$'\E[0;31m'
NC=$'\E[0m'
GREEN=$'\E[0;32m'
sed "s/No/${RED}No${NC}/g ; s/Yes/${GREEN}Yes${NC}/g" file.txt > color_file.txt
cat color_file.txt

Or maybe you wanted printf to interpret the escpe sequences in the content of a file:

RED='\033[0;31m'
NC='\033[0m'
GREEN='\033[0;32m'
sed "s/No/${RED}No${NC}/g ; s/Yes/${GREEN}Yes${NC}/g" file.txt > color_file.txt
printf "%b\n" "$(cat color_file.txt)"
# or maybe:
xargs -0 printf "%b" < color_file.txt
# or maybe:
sed 's/\\033/\e/g' color_file.txt
# etc.

Check your scripts with shellcheck - it will tell you about all mistakes that you did.

's/No/${RED}...'

Variable expansion does not expand within single quotes.

#If you would:
RED='\033[0;31m'
.... sed "....${RED}..."

sed does not interpret octal escape sequences. For sed the string \033 is a zero byte 0x00 followed by two 33.

printf "$(cat ...)"

Is an antipattern. Just execute cat ....

cat ... | sed..

Is a useless use of cat.

how to make printf read the content of the file

It is not possible to read a file with printf. It's not a tool for that.

and therefore execute the commands within it.

This feels unrelated to your issue, but to execute a file just call it with an interpreter sh ./file.sh or source it within current execution environment . ./file.sh.

How to print to console in color?

Define color like this:

W  = '\033[0m'  # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple

print(R+"hello how are you"+W)

Demo:
Demo

see all color codes here:Color Codes



Related Topics



Leave a reply



Submit