如何在控制台中打印彩色文字?

12

如何使用Python打印彩色文本。例如

print('This should be red')
print('This should be green')

现在一切都是白色的文字在黑色的背景上。我使用Ubuntu,如果这有帮助。


2
https://dev59.com/92bWa4cB1Zd3GeqPYJJZ - PeterMmm
5个回答

44

像这样定义颜色:

W  = '\033[0m'  # white (normal)
R  = '\033[31m' # red
G  = '\033[32m' # green
O  = '\033[33m' # orange
B  = '\033[34m' # blue
P  = '\033[35m' # purple

print(R+"hello how are you"+W)

示例: 示例

在这里查看所有颜色代码:颜色代码


在Windows上,您可能还需要colorama软件包(请参见此问题的重复内容)。 - Tomasz Gandor
这个解决方案在Anaconda提示符中不起作用。 - DovaX

4

4
下面是我认为有用的一个函数。它将使用标准RGB元组打印您提供的文本,并使用您指定的所需前景和背景颜色,因此您无需记住ANSI代码即可使用。要查找可能想要使用的RGB值,您可以使用颜色选择器
def print_in_color(txt_msg,fore_tupple,back_tupple,):
    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple 
    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)
    rf,gf,bf=fore_tupple
    rb,gb,bb=back_tupple
    msg='{0}' + txt_msg
    mat='\33[38;2;' + str(rf) +';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) +'m' 
    print(msg .format(mat))
    print('\33[0m') # returns default print color to back to black

# example of use using a message with variables
fore_color='cyan'
back_color='dark green'
msg='foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255),(0,127,127))

应该是"rf,gf,bf=fore_tupple",而不是"rf,bf,gf=fore_tupple"。 - ZDL-so
@GerryP 这真是太棒了,非常感谢。 - Guimoute
优秀的方法是:使用单个 print 命令将消息打印并返回默认的黑色打印颜色,从而避免出现空白行:print(msg .format(mat) + '\33[0m' ) - Max

1
使用像 colorconsole 这样的模块更容易:
pip install colorconsole

然后例如。

from colorconsole import terminal

screen = terminal.get_terminal(conEmu=False)

screen.cprint(4, 0, "This is red\n")
screen.cprint(10, 0, "This is light green\n")
screen.cprint(0, 11, "This is black on light cyan\n")

screen.reset_colors()

它还支持256/24位颜色(如果可用)。

0
使用这个函数在这里:它有红色、蓝色和绿色。
colors = {'red':'\033[31m', 'blue':'\033[34m', 'green':'\033[32m'}

def colorprint(string, text_color = 'default', bold = False, underline = False):
    if underline == True:
            string = '\033[4m' + string
    if bold == True:
            string = '\033[1m' + string
    if text_color == 'default' or text_color in colors:
            for color in colors:
                    if text_color == color:
                            string = colors[color] + string
    else:
            raise ValueError ("Colors not in:", colors.keys())

    print(string + '\033[0m')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接