【发布时间】:2023-03-08 06:41:01
【问题描述】:
我有一个简单的打印语句:
print('hello friends')
我希望终端中的输出为蓝色。如何使用 Python3 完成此任务?
【问题讨论】:
-
目前不清楚您的问题是什么。
-
你可以使用these类。
标签: python-3.x printing colors
我有一个简单的打印语句:
print('hello friends')
我希望终端中的输出为蓝色。如何使用 Python3 完成此任务?
【问题讨论】:
标签: python-3.x printing colors
我使用colors 模块。克隆 git 存储库,运行 setup.py 就可以了。然后,您可以像这样轻松地打印带有颜色的文本:
import colors
print(colors.red('this is red'))
print(colors.green('this is green'))
这适用于命令行,但可能需要进一步配置 IDLE。
【讨论】:
colorama 非常简单,只需这样做:
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")
这是 Python3 REPL 中的运行结果:
并调用它来重置颜色设置:
print(Style.RESET_ALL)
为避免打印空行,请编写以下代码:
print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")
【讨论】:
这是我用来在 Python 3 脚本中为特定输出着色的一类。您可以导入该类并像这样使用:
from colorprint import ColorPrint as _
_.print_fail('Error occurred, quitting program')
import sys
# Colored printing functions for strings that use universal ANSI escape sequences.
# fail: bold red, pass: bold green, warn: bold yellow,
# info: bold blue, bold: bold white
class ColorPrint:
@staticmethod
def print_fail(message, end = '\n'):
sys.stderr.write('\x1b[1;31m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_pass(message, end = '\n'):
sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_warn(message, end = '\n'):
sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_info(message, end = '\n'):
sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)
@staticmethod
def print_bold(message, end = '\n'):
sys.stdout.write('\x1b[1;37m' + message.strip() + '\x1b[0m' + end)
【讨论】:
我从较早的 python2 答案中得到的这个答案是
安装 termcolor 模块。
pip3 install termcolor
从 termcolor 导入彩色库。
from termcolor import colored
使用提供的方法,下面是一个示例。
print(colored('hello', 'red'), colored('world', 'green'))
【讨论】:
ESC[31mhelloESC[0m ESC[32mworldESC[0m
我想向您展示如何为代码着色。如果您想在下面玩它,还有一个游戏。如果您愿意,请复制和粘贴,并确保每个人都有美好的一天!此外,这适用于 Python 3,而不是 2。 (游戏)
# The Color Game!
# Thank you for playing this game.
# Hope you enjoy and please do not copy it. Thank you!
#
import colorama
from colorama import Fore
score = 0
def Check_Answer(answer):
if (answer == "no"):
print('correct')
return True
else:
print('wrong')
answer = input((Fore.RED + "This is green."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
answer = input((Fore.BLACK + "This is red."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
answer = input((Fore.BLUE + "This is black."))
if Check_Answer(answer) == True:
score = score + 1
else:
pass
print('Your Score is ', score)
现在是颜色编码。它还附带了您可以尝试的颜色列表。
# Here is how to color code in Python 3!
# Some featured color codes are : RED, BLUE, GREEN, YELLOW, OR WHITE. I don't think purple or pink are not out yet.
# Here is how to do it. (Example is down below!)
import colorama
from colorama import Fore
print(Fore.RED + "This is red..")
【讨论】:
将这些类放入 test.py 文件附近的 Color.py 文件中,然后运行 test.py。 我已经在 Ubuntu Server 16.04 和 Linux Mint 18.2 上测试了这些类。除了 GColor (RGB) 之外,所有类都运行良好,它可以在 Linux Mint 终端等图形终端中使用。 此外,您可以像这样使用这些类:
print(Formatting.Italic + ANSI_Compatible.Color(12) + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold + "!" + ANSI_Compatible.END + Formatting.Reset)
print(Color.B_DarkGray + Color.F_LightBlue + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold + "!" + Base.END)
结果:
注意:它不适用于 Windows!
文件Color.py:
class Base:
# Foreground:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
# Formatting
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# End colored text
END = '\033[0m'
NC ='\x1b[0m' # No Color
class ANSI_Compatible:
END = '\x1b[0m'
# If Foreground is False that means color effect on Background
def Color(ColorNo, Foreground=True): # 0 - 255
FB_G = 38 # Effect on foreground
if Foreground != True:
FB_G = 48 # Effect on background
return '\x1b[' + str(FB_G) + ';5;' + str(ColorNo) + 'm'
class Formatting:
Bold = "\x1b[1m"
Dim = "\x1b[2m"
Italic = "\x1b[3m"
Underlined = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
# Reset part
Reset = "\x1b[0m"
Reset_Bold = "\x1b[21m"
Reset_Dim = "\x1b[22m"
Reset_Italic = "\x1b[23m"
Reset_Underlined = "\x1b[24"
Reset_Blink = "\x1b[25m"
Reset_Reverse = "\x1b[27m"
Reset_Hidden = "\x1b[28m"
class GColor: # Gnome supported
END = "\x1b[0m"
# If Foreground is False that means color effect on Background
def RGB(R, G, B, Foreground=True): # R: 0-255 , G: 0-255 , B: 0-255
FB_G = 38 # Effect on foreground
if Foreground != True:
FB_G = 48 # Effect on background
return "\x1b[" + str(FB_G) + ";2;" + str(R) + ";" + str(G) + ";" + str(B) + "m"
class Color:
# Foreground
F_Default = "\x1b[39m"
F_Black = "\x1b[30m"
F_Red = "\x1b[31m"
F_Green = "\x1b[32m"
F_Yellow = "\x1b[33m"
F_Blue = "\x1b[34m"
F_Magenta = "\x1b[35m"
F_Cyan = "\x1b[36m"
F_LightGray = "\x1b[37m"
F_DarkGray = "\x1b[90m"
F_LightRed = "\x1b[91m"
F_LightGreen = "\x1b[92m"
F_LightYellow = "\x1b[93m"
F_LightBlue = "\x1b[94m"
F_LightMagenta = "\x1b[95m"
F_LightCyan = "\x1b[96m"
F_White = "\x1b[97m"
# Background
B_Default = "\x1b[49m"
B_Black = "\x1b[40m"
B_Red = "\x1b[41m"
B_Green = "\x1b[42m"
B_Yellow = "\x1b[43m"
B_Blue = "\x1b[44m"
B_Magenta = "\x1b[45m"
B_Cyan = "\x1b[46m"
B_LightGray = "\x1b[47m"
B_DarkGray = "\x1b[100m"
B_LightRed = "\x1b[101m"
B_LightGreen = "\x1b[102m"
B_LightYellow = "\x1b[103m"
B_LightBlue = "\x1b[104m"
B_LightMagenta = "\x1b[105m"
B_LightCyan = "\x1b[106m"
B_White = "\x1b[107m"
还有,
文件test.py:
from Color import *
if __name__ == '__main__':
print("Base:")
print(Base.FAIL,"This is a test!", Base.END)
print("ANSI_Compatible:")
print(ANSI_Compatible.Color(120),"This is a test!", ANSI_Compatible.END)
print("Formatting:")
print(Formatting.Bold,"This is a test!", Formatting.Reset)
print("GColor:") # Gnome terminal supported
print(GColor.RGB(204,100,145),"This is a test!", GColor.END)
print("Color:")
print(Color.F_Cyan,"This is a test!",Color.F_Default)
结果:
在 Ubuntu 服务器 16.04 上
在 Linux Mint 18.2 上
【讨论】:
对于 Windows,只需这样做:
import os
os.system("color 01")
print('hello friends')
其中“01”表示背景为黑色,文本颜色为蓝色。进入 CMD 提示并输入颜色帮助以获取颜色列表。
【讨论】:
试试这个方法,不用导入模块,只用颜色代码号,定义为常量:
BLUE = '34m'
message = 'hello friends'
def display_colored_text(color, text):
colored_text = f"\033[{color}{text}\033[00m"
return colored_text
例子:
>>> print(display_colored_text(BLUE, message))
hello friends
【讨论】:
# 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):
for col in range(6):
color = row*6 + col + 4
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(" ", end=" ")
for row in range(-1,42):
print_six(row, fg)
print("",end=" ")
print_six(row, bg)
print()
# Simple usage: print(fg("text", 160))
【讨论】:
7、30–47 和 90–107 在 Pycharm 中着色。 4 有下划线,41 是粉红色的。两列是相同的,这意味着30–39 和90–99 具有前景色,而40–47 和100–107 具有背景色。
由于 Python 是在 C 中解释和运行的,因此可以在没有模块的情况下设置颜色。
你可以像这样为颜色定义一个类:
class color:
PURPLE = '\033[1;35;48m'
CYAN = '\033[1;36;48m'
BOLD = '\033[1;37;48m'
BLUE = '\033[1;34;48m'
GREEN = '\033[1;32;48m'
YELLOW = '\033[1;33;48m'
RED = '\033[1;31;48m'
BLACK = '\033[1;30;48m'
UNDERLINE = '\033[4;37;48m'
END = '\033[1;37;0m'
写代码的时候,可以简单的写:
print(color.BLUE + "你好朋友" + color.END)
请注意,您选择的颜色必须像您的类定义一样大写,这些是我个人认为令人满意的颜色选择。如需更全面的颜色选择,实际上还有背景选择,请参阅:https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a。
这是 C 代码,但一旦您了解代码的编写方式,就可以轻松适应 Python。
以 BLUE 为例,因为这是您想要显示的内容。
BLUE = '033[1;37;48m'
\033 告诉 Python 中断并注意以下格式。
1 通知代码加粗。 (我更喜欢 1 到 0,因为它弹出更多。)
34 是实际的颜色代码。它选择蓝色。
48m 是背景颜色。 48m和控制台窗口一样的阴影,所以看起来没有背景。
【讨论】:
print("{} hello friends {}".format(color.BLUE, color.END)),因为它更具可读性。
无需安装任何额外的库,它与我所知道的每一个终端都兼容。
类方法:
先做import config as cfg。
clipped 是数据框。
#### HEADER: ####
print('{0:<23} {1:>24} {2:>26} {3:>26} {4:>11} {5:>11}'.format('Road name','Classification','Function','Form of road','Length','Distance') )
#### Now row by row: ####
for index, row in clipped.iterrows():
rdName = self.colorize(row['name1'],cfg.Green)
rdClass = self.colorize(row['roadClassification'],cfg.LightYellow)
rdFunction = self.colorize(row['roadFunction'],cfg.Yellow)
rdForm = self.colorize(row['formOfWay'],cfg.LightBlue)
rdLength = self.colorize(row['length'],cfg.White)
rdDistance = self.colorize(row['distance'],cfg.LightCyan)
print('{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}'.format(rdName,rdClass,rdFunction,rdForm,rdLength,rdDistance) )
{0:<30} {1:>35} {2:>35} {3:>35} {4:>20} {5:>20}的含义:
0, 1, 2, 3, 4, 5 -> 列,本例一共6列
30, 35, 20 -> 列宽(请注意,您必须添加 \033[96m 的长度 - 这对于 Python 也是一个字符串),只是实验 :)
>, < -> justify: right, left(= 也用于填充零)
config.py:中有什么内容
#colors
ResetAll = "\033[0m"
Bold = "\033[1m"
Dim = "\033[2m"
Underlined = "\033[4m"
Blink = "\033[5m"
Reverse = "\033[7m"
Hidden = "\033[8m"
ResetBold = "\033[21m"
ResetDim = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink = "\033[25m"
ResetReverse = "\033[27m"
ResetHidden = "\033[28m"
Default = "\033[39m"
Black = "\033[30m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
LightGray = "\033[37m"
DarkGray = "\033[90m"
LightRed = "\033[91m"
LightGreen = "\033[92m"
LightYellow = "\033[93m"
LightBlue = "\033[94m"
LightMagenta = "\033[95m"
LightCyan = "\033[96m"
White = "\033[97m"
【讨论】:
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def colour_print(text,colour):
if colour == 'OKBLUE':
string = bcolors.OKBLUE + text + bcolors.ENDC
print(string)
elif colour == 'HEADER':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'OKCYAN':
string = bcolors.OKCYAN + text + bcolors.ENDC
print(string)
elif colour == 'OKGREEN':
string = bcolors.OKGREEN + text + bcolors.ENDC
print(string)
elif colour == 'WARNING':
string = bcolors.WARNING + text + bcolors.ENDC
print(string)
elif colour == 'FAIL':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'BOLD':
string = bcolors.BOLD + text + bcolors.ENDC
print(string)
elif colour == 'UNDERLINE':
string = bcolors.UNDERLINE + text + bcolors.ENDC
print(string)
只需复制上面的代码。 给他们打电话很容易
colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')
希望对你有帮助
【讨论】:
最简单、最直接的答案似乎是这样的:
print('\033[94m' + 'hello friends' + '\033[0m')
然而,这个答案很难提出,因为:
'\033[94m' 是什么??对我们人类来说还不够好)安装colorama 或termcolor 之类的东西可能是一种方法。然而:
这里的一些答案已经暗示了这种方法。基本上,只需将外星人代码(例如\033[95m、\033[94m、\033[0m、...)转储到类的属性中,然后使用类属性的名称构建字符串。示例:
class Colors:
OKBLUE='\033[94m'
ENDC='\033[0m'
print(Colors.OKBLUE + 'hello friends' + Colors.END)
这解决了问题,并允许在需要时为其他颜色添加更多外来代码。在许多项目中,这种方法已经足够好了。
但是,在某些项目中,这种方法效果不佳。当我们一遍又一遍地使用Colors 类时,编写字符串连接的整个过程(使用加法或等效方法)在降低您的代码可读性方面变得有点问题。
一个好的 API 可能是这样的:
from utils import Colors # `utils` is a fictional module where we would have our `Colors` class
greeting = Colors.okblue('hello friends')
print(greeting)
# Or even shorter
Colors.print_okblue('hello friends')
在此示例中,.okblue(...) 和 .print_okblue(...) 是类方法,它们通过将方法名称自动转换为相应的外来代码来提供快捷方式。这种快捷方式可以使用类似__getattr__ 自定义的方式来实现。
但是,我尝试在 Colors 类中这样做,但效果不佳,因为我需要创建 Colors 类 (colors = Colors()) 的实例才能使用快捷方式方法。相反,我想继续使用这些方法作为类方法。因此,我不得不选择元类。
假设我们有以下utils.py:
from functools import partial
class _MetaColors(type):
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
BOLD = '\033[1m'
B = '\033[1m'
UNDERLINE = '\033[4m'
U = '\033[4m'
_ENDC = '\033[0m'
def __getattr__(cls, name):
if name.startswith('print_'):
key = name.lstrip('print_').upper()
assert not key.startswith('_'), 'Color key cannot start with `_`'
return partial(cls.print, key)
else:
key = name.upper()
assert not key.startswith('_'), 'Color key cannot start with `_`'
return partial(cls.colorize, key)
@classmethod
def colorize(cls, key, *args):
ini = getattr(cls, key.upper(), None)
assert ini != None, f'Color key "{key}" not recognized'
string = ' '.join(str(a) for a in args)
return ini + string + cls._ENDC
@classmethod
def print(cls, key, *args, **kwds):
colorized = cls.colorize(key, *args)
print(colorized, **kwds)
class Colors(metaclass=_MetaColors):
pass
然后,您可以像这样使用其他模块中的颜色:
from utils import Colors
print(Colors.okblue('hello friends'))
# or
greeting = Colors.okblue('hello friends')
print(greeting)
print('hello', Colors.okblue('friends'))
print(f'hello {Colors.okblue("friends")}')
Colors.print_okblue('hello friends')
【讨论】: