Python Colorama 打印所有颜色

7

我是Python学习的新手,发现了colorama。作为一个测试项目,我想打印出所有可用的colorama颜色。

from colorama import Fore
from colorama import init as colorama_init

colorama_init(autoreset=True)

colors = [x for x in dir(Fore) if x[0] != "_"]
for color  in colors:
    print(color + f"{color}")

当然,这会输出完全黑色的输出结果,如下所示:
BLACKBLACK
BLUEBLUE
CYANCYAN
...

由于Dir(Fore)只会给出Fore.BLUE, Fore.GREEN等颜色属性的字符串表示形式,所以有没有一种方法可以访问所有的前景色属性,使它们实际起作用:

print(Fore.BLUE + "Blue")

换句话说,这可能更好地表达了我的问题。

我想写下这个:

print(Fore.BLACK + 'BLACK')
print(Fore.BLUE + 'BLUE')
print(Fore.CYAN + 'CYAN')
print(Fore.GREEN + 'GREEN')
print(Fore.LIGHTBLACK_EX + 'LIGHTBLACK_EX')
print(Fore.LIGHTBLUE_EX + 'LIGHTBLUE_EX')
print(Fore.LIGHTCYAN_EX + 'LIGHTCYAN_EX')
print(Fore.LIGHTGREEN_EX + 'LIGHTGREEN_EX')
print(Fore.LIGHTMAGENTA_EX + 'LIGHTMAGENTA_EX')
print(Fore.LIGHTRED_EX + 'LIGHTRED_EX')
print(Fore.LIGHTWHITE_EX + 'LIGHTWHITE_EX')
print(Fore.LIGHTYELLOW_EX + 'LIGHTYELLOW_EX')
print(Fore.MAGENTA + 'MAGENTA')
print(Fore.RED + 'RED')
print(Fore.RESET + 'RESET')
print(Fore.WHITE + 'WHITE')
print(Fore.YELLOW + 'YELLOW')

简而言之:

for color in all_the_colors_that_are_available_in_Fore:
    print('the word color in the representing color')
    #or something like this?
    print(Fore.color + color)
3个回答

8
它打印颜色名称两次的原因在Patrick的评论中有很好的解释。
有没有一种方法可以访问所有前景色属性,使它们像这样实际工作?
根据:https://pypi.org/project/colorama/ 您可以使用其他方式打印带有颜色的字符串,而不是例如 print(Fore.RED + 'some red text') 您可以使用termcolor模块中的colored函数来对字符串着色。但并非所有的Fore颜色都受支持,所以您可以这样做:
from colorama import Fore
from colorama import init as colorama_init
from termcolor import colored

colorama_init(autoreset=True)

colors = [x for x in dir(Fore) if x[0] != "_"]
colors = [i for i in colors if i not in ["BLACK", "RESET"] and "LIGHT" not in i] 

for color  in colors:
    print(colored(color, color.lower()))

希望这个回答解决了你的问题。
编辑:
我读了更多关于“Fore”项的信息,发现您可以检索一个包含每种颜色作为键和其代码作为值的字典,因此您可以执行以下操作以包括“Fore”中的所有颜色:
from colorama import Fore
from colorama import init as colorama_init

colorama_init(autoreset=True)

colors = dict(Fore.__dict__.items())

for color in colors.keys():
    print(colors[color] + f"{color}")


谢谢您的回答,它很有效。但并不适用于所有颜色。比如浅色调的颜色。 - Gerrit Geeraerts
我刚刚编辑了我的答案来解决这个问题,请检查一下 :) - Kasper
你好,能告诉我如何添加自定义颜色吗?比如我想使用橙色和灰色,但它们不在列表中。 - Abdul Haseeb
1
@AbdulHaseeb 在这种情况下,您需要使用颜色代码,请查看此问题 - Kasper

0

你也可以使用 eval()。

for i in listOfColors:
    color = "Fore." + i
    print(eval(color), i)
    print(Style.RESET_ALL, end='') #end='' prevents extra newlines

0
你可以使用getattr函数。
from colorama import Fore
from colorama import init as colorama_init

colorama_init(autoreset=True)

colors = [x for x in dir(Fore) if x[0] != "_" and "LIGHT" not in x]
for color in colors:
    print(getattr(Fore, color) + f"{color}")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接