在 for 循环中,有没有办法使用 for 循环分配的属性执行模块函数?

In for loops, is there a way to execute a module function with attributes assigned by the for loop?

Python 3.10.1

编程新手,请耐心等待。

我想打印 colorama 模块中可用的所有前景色的列表,颜色命名如下:

PowerShell Colors

我的尝试:

from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")

我的输出(没有颜色变化):

  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]

抱歉,我进行了更多搜索,发现了用户 Kasper 的 ,我以前找不到,我将其实现到我的代码中,如下所示:

from colorama import init, Fore, Style
init()

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

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

试试这个:

from colorama import Fore, Style

# available foreground colors acquired via dir(Fore)
colors = {
    "BLACK": Fore.BLACK,
    "BLUE": Fore.BLUE,
    "CYAN": Fore.CYAN,
    "GREEN": Fore.GREEN,
    "LIGHTBLACK_EX": Fore.LIGHTBLACK_EX,
    "LIGHTBLUE_EX": Fore.LIGHTBLUE_EX,
    "LIGHTCYAN_EX": Fore.LIGHTCYAN_EX,
    "LIGHTGREEN_EX": Fore.LIGHTGREEN_EX,
    "LIGHTMAGENTA_EX": Fore.LIGHTMAGENTA_EX,
    "LIGHTRED_EX": Fore.LIGHTRED_EX,
    "LIGHTWHITE_EX": Fore.LIGHTWHITE_EX,
    "LIGHTYELLOW_EX": Fore.LIGHTYELLOW_EX,
    "MAGENTA": Fore.MAGENTA,
    "RED": Fore.RED,
    "WHITE": Fore.WHITE,
    "YELLOW": Fore.YELLOW
}

for col in colors:
    print(f"{colors[col]}[{col}]{Style.RESET_ALL}")

这就是您获得所需输出的方式:

from colorama import Fore

colors = [c for c in dir(Fore) if not c.startswith('__')]

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

这里发生的是当你赋值时:

"Fore." + col

到fcol变量,它被存储为一个字符串。这意味着当您尝试 运行 它时,它将被视为字符串而不是函数。 您所做的是正确的,但您只需要添加一个 eval() 函数,以便 Python 将您的 Fore.col 评估为一个函数。

for col in colors:
    fcol = "Fore." + col
    fcol = eval(fcol)

此外,您在最后一行错误地使用了 exec() 函数。应该这样做:

print(f"{fcol}[{col}]{Style.RESET_ALL}")

一个简单的方法是:

print(fcol+ col, Style.RESET_ALL)