Ger*_*rts 9 python properties colorama
我是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}")
Run Code Online (Sandbox Code Playgroud)
当然,这会输出全黑输出,如下所示:
BLACKBLACK
BLUEBLUE
CYANCYAN
...
Run Code Online (Sandbox Code Playgroud)
因为 Dir(Fore) 只是给了我Fore.BLUE, Fore.GREEN, ...的字符串表示形式
有没有办法访问所有前景色属性,以便它们实际工作,如下所示:
print(Fore.BLUE + "Blue")
Run Code Online (Sandbox Code Playgroud)
或者换句话说,这可能更好地表达我的问题。
我想写这个:
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')
Run Code Online (Sandbox Code Playgroud)
简而言之:
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)
Run Code Online (Sandbox Code Playgroud)
帕特里克对这个问题的评论很好地描述了两次打印颜色名称的原因。
Is their a way to access all the Fore Color property so they actualy work as in
根据: https: //pypi.org/project/colorama/
您可以使用其他方式打印彩色字符串,例如print(Fore.RED + 'some red text')
您可以使用模块中的彩色函数termcolor,该函数采用字符串和颜色来对该字符串进行着色。但并非所有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()))
Run Code Online (Sandbox Code Playgroud)
希望这能回答您的问题。
编辑:
我阅读了有关项目的更多信息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}")
Run Code Online (Sandbox Code Playgroud)