如何打印到彩色控制台?

use*_*650 6 python ubuntu

如何使用python打印以彩色打印.例如

print('This should be red')
print('This should be green')
Run Code Online (Sandbox Code Playgroud)

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

Hac*_*lic 19

定义这样的颜色:

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)
Run Code Online (Sandbox Code Playgroud)

演示: 演示

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


Ger*_*y P 5

下面是我觉得有用的一个方便的功能。它将以您使用标准 RGB 元组指定的所需前景色和背景色打印您提供的文本,因此您不必记住 ANSI 代码。要查找您可能想要使用的 RGB 值,您可以使用 https://www.w3schools.com/colors/colors_picker.asp上的颜色选择器。

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))
Run Code Online (Sandbox Code Playgroud)