Python | change text color in shell

Question:

I was wondering if anyone knows how to set the color of the text that shows up in the shell. I noticed the ‘ls’ uses a couple different colors when printing out information to the screen (on my Linux box), was wondering if I could take advantage of that in Python.

Asked By: johannix

||

Answers:

All the major color codes are given at https://www.siafoo.net/snippet/88

Answered By: Matthew Flaschen

curses will allow you to use colors properly for the type of terminal that is being used.

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here’s a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
Answered By: Dietrich Epp

This is so simple to do on a PC: Windows OS:
Send the os a command to change the text:
import os

os.system('color a') #green text
print 'I like green' 
raw_input('do you?')
Answered By: Day Marquez

I just described very popular library clint. Which has more features apart of coloring the output on terminal.

By the way it support MAC, Linux and Windows terminals.

Here is the example of using it:

Installing (in Ubuntu)

pip install clint

To add color to some string

colored.red('red string')

Example: Using for color output (django command style)

from django.core.management.base import BaseCommand
from clint.textui import colored


class Command(BaseCommand):
    args = ''
    help = 'Starting my own django long process. Use ' + colored.red('<Ctrl>+c') + ' to break.'

    def handle(self, *args, **options):
        self.stdout.write('Starting the process (Use ' + colored.red('<Ctrl>+c') + ' to break)..')
        # ... Rest of my command code ...
Answered By: Kostanos
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.