如何用彩色打印到控制台?

2024-09-25 16:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python print进行彩色打印。例如

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

现在一切都是黑底白字。我用ubuntu,如果有帮助的话。


Tags: ubuntugreenredbethis彩色printshould
3条回答

定义如下颜色:

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

使用诸如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位颜色。

使用彩色模块。

import colored
color = colored.fg(196) #orange
print(color + "This text is orange")

https://pypi.org/project/colored/

相关问题 更多 >