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.
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.
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.
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)
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With