如何在Python中将彩色文本输出到终端?
当前回答
在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)
其他回答
# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
# Simple usage: print(fg("text", 160))
在线试用
我能找到的最简单的方法不是使用ANSI转义码,而是使用导入模块colorama中的Fore。看看下面的代码:
from colorama import Fore, Style
print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")
print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")
与ANSI转义码相比:
print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")
print("BACK TO NORMALZ.")
下面是一个可以这样使用的实现:
from stryle import Stryle
print(Stryle.okgreen.bold@"Hello World" + Stryle.underline@'!' + ' back to normal')
print(f"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}")
print("Merry "@Stryle.red + "Christmas"@Stryle.okgreen.underline)
_decorations = {
"header" : '\033[95m',
"okblue" : '\033[94m',
"okcyan" : '\033[96m',
"okgreen" : '\033[92m',
"yellow" : '\033[93m',
"red" : '\033[91m',
"warning" : '\033[93m',
"fail" : '\033[91m',
"off" : '\033[0m',
"bold" : '\033[1m',
"underline" : '\033[4m',
}
class _StringStyle(str):
def __getattribute__(self, decoration: str = _decorations["off"]):
if decoration in _decorations:
return _StringStyle(self.decorations + _decorations[decoration])
return self
def __matmul__(self, other):
return self.decorations + str(other) + _decorations["off"]
def __rmatmul__(self, other):
return self.decorations + str(other) + _decorations["off"]
def __str__(self):
return self.decorations
Stryle = _StringStyle()
import click
click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)
click(CLI库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。
使用pyfancy。这是一种在终端中进行颜色处理的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)