0

Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

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}")

My output (no color changes):

  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]

4 Answers4

1

What's happening here is when you assign:

"Fore." + col

to the fcol variable, it is stored as a string. This means that when you try to run it, it would be treated like a string and not a function. What you did is correct, but you just have to add an eval() function so that Python evaluates your Fore.col as a function.

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

Also, you used the exec() function incorrectly in the last line. It should be done like this:

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

A simple way of doing this would be:

print(fcol+ col, Style.RESET_ALL)
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
prokan
  • 21
  • 2
0

Apologies, I searched around some more and found an answer by user Kasper I couldn't before, which I implemented to my code like so:

from colorama import init, Fore, Style
init()

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

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

Try this:

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}")
Asdoost
  • 316
  • 1
  • 2
  • 15
0

This is how you get your desired output:

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}]" )

enter image description here

tjallo
  • 781
  • 6
  • 25