Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python | change text color in shell [duplicate]

Tags:

python

shell

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.

like image 685
johannix Avatar asked Feb 24 '10 22:02

johannix


People also ask

How do you change the color of text in Python shell?

Method 1: Using ANSI ESCAPE CODE To add color and style to text, you should create a class called ANSI, and inside this class, declare the configurations about the text and color with code ANSI. Functions Used: background: allows background formatting.

How do I change the color of text in terminal?

Open any new terminal and open Preferences dialog box by selecting Edit and Preferences menu item. Click on the Colors tab of the Preferences dialog box. There is an option for text and background color and that is “Use color from system theme”. This option is enabled by default.


2 Answers

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%s\x1b[0m' % (';'.join(attr), string) 
like image 160
Dietrich Epp Avatar answered Oct 16 '22 15:10

Dietrich Epp


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 ... 
like image 20
Kostanos Avatar answered Oct 16 '22 16:10

Kostanos