2014-12-03 171 views
4

如何使用python打印以彩色打印。例如如何以彩色打印控制檯?

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

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

+2

http://stackoverflow.com/questions/11672876/colored-console-output-in-linux – PeterMmm 2014-12-03 06:49:07

+1

[用終端打印顏色使用Python?](http://stackoverflow.com/questions/287871)/print-in-terminal-with-colors-using-python) – Rufflewind 2014-12-03 06:59:49

回答

16

這樣定義顏色:

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) 

演示: Demo

看到所有的顏色代碼在這裏:Color Codes

+1

你應該提供一個鏈接到顏色代碼。 – 2014-12-03 07:07:03

+0

在windows上,你可能還需要'colorama'包(參見這個重複的問題)。 – 2017-12-06 22:27:08

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位顏色(如果可用)。