Simple colored output in python 3 using termcolor

Visually scanning long lines of output can cause the eye to lose track of the line you are interested in. Wouldn’t it be nice if you could simulate lineprinter paper? In this article, I’ll show you how with termcolor. It’s easy. Here’s a sample result:

color

You need to install the termcolor package:
pip3 install termcolor

Here is the the python code that generates the output:

from termcolor import colored # pip3 install termcolor
# try piping through 'less -r'

seq = map(lambda x: "{0:>2} {1}".format(str(x), "*" * x), range(50))

for i, text in enumerate(seq):
    if i % 3 == 0:
        text = colored(text, "grey", "on_green")
    print(text)

As you can see, it’s very simple. In the variable ‘seq’, I just generated a list of inputs, which is just some line numbers and some asterices. You would just replace it by your own list of lines. The for loop is what actually does the colouring. Every third line has its text colored.

If you want to pipe the output through ‘less’ then you will need to enable the raw control chars option, like so:

python3 mycolors.py | less -r

Be sure to check the link above for more details about how to use the module. Happy programming!

Advertisements

About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Python and tagged , , . Bookmark the permalink.

One Response to Simple colored output in python 3 using termcolor

  1. Pingback: green: a tiny util for turning every third line green | Mark Carter's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s