Python | 在终端中改变文本颜色
我在想,有没有人知道怎么设置在终端里显示的文字颜色。我注意到在我的Linux电脑上,'ls'命令在打印信息到屏幕时会用几种不同的颜色。我想知道我能不能在Python里利用这个功能。
6 个回答
5
所有主要的颜色代码都可以在这个链接找到:https://www.siafoo.net/snippet/88
12
我刚刚介绍了一个非常受欢迎的库,叫做 clint。这个库除了可以给终端的输出加颜色,还有很多其他功能。
顺便说一下,它支持MAC、Linux和Windows的终端。
下面是使用它的例子:
在Ubuntu上安装
pip install clint
给某个字符串添加颜色
colored.red('red string')
示例:用于彩色输出(类似django命令的风格)
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 ...
56
可以使用Curses库或者ANSI转义序列。在你开始使用转义序列之前,最好先确认一下标准输出(stdout)是不是一个终端(tty)。你可以用 sys.stdout.isatty()
来检查。下面是我一个项目里提取的函数,它根据状态使用ANSI转义序列来打印红色或绿色的输出:
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)