如何在Python中将彩色文本输出到终端?
当前回答
我的两分钱(PyColorTerm):
安装:
sudo apt-get install python-pip
pip install pycolorterm
Python脚本:
from pycolorterm import pycolorterm
with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
out.write('Works OK!')
“工作正常!”显示为绿色。
其他回答
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#
考虑到您是否正在编写命令行工具,这是最简单和方便的方法。这种方法可以在所有控制台上的任何地方工作,而无需安装任何花哨的软件包。
要使ANSI代码在Windows上运行,首先,运行os.system('color')
import os
os.system('color')
COLOR = '\033[91m' # change it, according to the color need
END = '\033[0m'
print(COLOR + "Hello World" + END) #print a message
exit=input() #to avoid closing the terminal windows
更多颜色:
注意:\33[5m和\33[6m闪烁。
感谢@qubodup
使用pyfancy。这是一种在终端中进行颜色处理的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
在windows 10中,您可以尝试使用这个小脚本,它用作颜色混合器,红色、绿色和蓝色的值为0-255:
import os
os.system('')
def RGB(red=None, green=None, blue=None,bg=False):
if(bg==False and red!=None and green!=None and blue!=None):
return f'\u001b[38;2;{red};{green};{blue}m'
elif(bg==True and red!=None and green!=None and blue!=None):
return f'\u001b[48;2;{red};{green};{blue}m'
elif(red==None and green==None and blue==None):
return '\u001b[0m'
并调用RGB函数使颜色的任意组合为:
g0 = RGB()
g1 = RGB(0,255,0)
g2 = RGB(0,100,0,True)+""+RGB(100,255,100)
g3 = RGB(0,255,0,True)+""+RGB(0,50,0)
print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")
不带参数的RGB()将清理并将前景/背景颜色设置为默认值。如果您想要黑色,则应将其称为RGB(0,0,0),白色RGB(255255255)。当RGB(0255,0)创建绝对绿色时,RGB(150255150)将生成浅绿色。
这支持背景色和前景色,要将颜色设置为背景色,必须使用bg=True传递,默认情况下为False。
例如:若要将红色设置为背景色,应将其称为RGB(255,0,0,True),但若要选择红色作为字体颜色,则只需将其命名为RGB(255,0,0,False),因为默认情况下bg为False,这将简化为仅将其称之为RGB(25.5,0,0)
您可以使用curses库的Python实现:curses-字符单元显示的终端处理
此外,运行此程序,您将找到您的盒子:
for i in range(255):
print i, chr(i)