我想知道是否有人知道如何设置显示在shell中的文本的颜色。我注意到'ls'在将信息输出到屏幕上(在我的Linux机器上)时使用了几种不同的颜色,我想知道我是否可以利用Python中的优势。Python |更改外壳中的文本颜色
回答
使用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)
所有主要的颜色代码是在https://www.siafoo.net/snippet/88
本网站的安全证书已经过期。任何人都可以验证这是一个安全的网站? – BlackVegetable 2012-02-16 23:43:24
@BlackVegetable,是的,它看起来和以前一样。此外,如果您愿意,您可以查看它[HTTP](http://www.siafoo.net/snippet/88)。我会联系他们让他们知道有关证书。 – 2012-02-17 00:42:05
即使你信任它,@BlackVegetable,你会得到一个代理错误 – 2016-07-14 16:57:22
curses
给定将让您正确使用颜色正在使用的终端类型。
我刚才所描述的非常流行的库clint 进口操作系统。除了着色终端上的输出外,还有更多的功能。
顺便说一句,它支持MAC,Linux和Windows终端。
下面是使用它的例子:
pip install clint
要添加颜色到一些字符串
colored.red('red string')
例
安装(在Ubuntu):使用用于颜色输出(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 ...
+1特别是对于'sys.stdout.isatty()' – Nifle 2010-02-24 22:59:11
对于输出不是tty的情况也有很好的覆盖,但是你仍然想要这种颜色 - 比方说你只是用sed或grep来过滤线条 – 2010-02-24 23:02:38
'unbuffer'可以做到这一点,所以如果没有覆盖就不会卡住。 – 2010-02-24 23:18:47