gpt4 book ai didi

python - 使用 python 打印彩色字符串到控制台

转载 作者:太空狗 更新时间:2023-10-29 21:19:04 30 4
gpt4 key购买 nike

有没有办法用 python 以彩色方式打印字符串?

例如,我可以将字符串 red 的某些部分或其他内容打印到控制台吗?我使用 Mac OS X。

最佳答案

这适用于支持颜色的 linux 控制台:

CODE={
'ENDC':0, # RESET COLOR
'BOLD':1,
'UNDERLINE':4,
'BLINK':5,
'INVERT':7,
'CONCEALD':8,
'STRIKE':9,
'GREY30':90,
'GREY40':2,
'GREY65':37,
'GREY70':97,
'GREY20_BG':40,
'GREY33_BG':100,
'GREY80_BG':47,
'GREY93_BG':107,
'DARK_RED':31,
'RED':91,
'RED_BG':41,
'LIGHT_RED_BG':101,
'DARK_YELLOW':33,
'YELLOW':93,
'YELLOW_BG':43,
'LIGHT_YELLOW_BG':103,
'DARK_BLUE':34,
'BLUE':94,
'BLUE_BG':44,
'LIGHT_BLUE_BG':104,
'DARK_MAGENTA':35,
'PURPLE':95,
'MAGENTA_BG':45,
'LIGHT_PURPLE_BG':105,
'DARK_CYAN':36,
'AUQA':96,
'CYAN_BG':46,
'LIGHT_AUQA_BG':106,
'DARK_GREEN':32,
'GREEN':92,
'GREEN_BG':42,
'LIGHT_GREEN_BG':102,
'BLACK':30,
}

def termcode(num):
return '\033[%sm'%num

def colorstr(astr,color):
return termcode(CODE[color])+astr+termcode(CODE['ENDC'])

if __name__=='__main__':
astr='yippy skippy'
# for num in range(300):
# color=termcode(num)
# print('%s: %s'%(num,color+astr+termcode(CODE['ENDC'])))
for key in sorted(CODE.keys()):
print('%s: %s'%(key,colorstr(astr,key)))

print(colorstr('Red','RED'))

下面是一个使用 colorstr 制作彩色记录器的例子:

import logging
import copy

logger=logging.getLogger(__name__)

class ColoredFormatter(logging.Formatter):
# A variant of code found at http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored
LEVELCOLOR = {
'DEBUG': 'BLUE',
'INFO': 'BLACK',
'WARNING': 'PURPLE',
'ERROR': 'RED',
'CRITICAL': 'RED_BG',
}

def __init__(self, msg):
logging.Formatter.__init__(self, msg)

def format(self, record):
record = copy.copy(record)
levelname = record.levelname
if levelname in self.LEVELCOLOR:
record.levelname = colorstr(levelname,self.LEVELCOLOR[levelname])
record.name = colorstr(record.name,'BOLD')
record.msg = colorstr(record.msg,self.LEVELCOLOR[levelname])
return logging.Formatter.format(self, record)

if __name__=='__main__':
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setFormatter(
ColoredFormatter('%(name)s: %(message)s (%(filename)s:%(lineno)d)'))
logger.addHandler(console)
fh = logging.FileHandler('/tmp/test.log','w')
fh.setFormatter(logging.Formatter('%(name)s: %(message)s'))
logger.addHandler(fh)

logger.debug('debug')
logger.info('info')
logger.warning('Warning')
logger.error('ERROR')
logger.critical('CRITICAL!!!')

此示例记录到控制台 (stderr) 和文件 (/tmp/test.log)。发送到控制台的消息是彩色的,但输出到文件的是纯文本。

关于python - 使用 python 打印彩色字符串到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696430/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com