change text color in shell
This question already has an answer here:
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)
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 ...
所有主要的颜色代码在https://www.siafoo.net/snippet/88上给出
链接地址: http://www.djcxy.com/p/87056.html下一篇: 更改shell中的文本颜色