How do I utilize the input() command to include ANSI escape color codes?
Question:
I’m relatively new to Python. I’m trying to utilize the input() function to include ANSI color codes, and store the values to a dictionary. I’ve tried using the colorama library too but wanted to try using this approach.
red = 'x1b[91m'
reset = 'x1b[0m'
color = input()
The user then types in the input: red+'test'+reset
which should return 'x1b[91mtestx1b[0m'
and printing this input via print(color)
should return the string ‘test’ that is colored red.
The input()
turns it into a string "red+'test'+rest"
instead. I’ve also tried directly typing in the ANSI code but I get the string "\x1b[91mtest\x1b[0m"
instead. Is there a way to format it so I can choose anywhere in the string to add colors? e.g. if I wanted this script to get inputs and function like:
"The "+yellow+"sun"+reset+" is bright in the "+blue+"sky"+reset+" today."
Answers:
Seems like you need eval
red = 'x1b[91m'
reset = 'x1b[0m'
color = eval(input('Enter something: '), {'red': red, 'reset': reset})
print(color)
Output:
Enter something: red + 'hi' + reset + 'bye'
Prints hibye
but the hi
is red and the bye
is white.
Note: eval
can be dangerous, don’t let the user enter something like __import__('shutil').rmtree('/')
– you might want to check the input before eval
uating. Adding '__builtins__': None
to the dictionary passed as the second parameter in eval
may make it a bit safer (as suggested by martineau)
I’m relatively new to Python. I’m trying to utilize the input() function to include ANSI color codes, and store the values to a dictionary. I’ve tried using the colorama library too but wanted to try using this approach.
red = 'x1b[91m'
reset = 'x1b[0m'
color = input()
The user then types in the input: red+'test'+reset
which should return 'x1b[91mtestx1b[0m'
and printing this input via print(color)
should return the string ‘test’ that is colored red.
The input()
turns it into a string "red+'test'+rest"
instead. I’ve also tried directly typing in the ANSI code but I get the string "\x1b[91mtest\x1b[0m"
instead. Is there a way to format it so I can choose anywhere in the string to add colors? e.g. if I wanted this script to get inputs and function like:
"The "+yellow+"sun"+reset+" is bright in the "+blue+"sky"+reset+" today."
Seems like you need eval
red = 'x1b[91m'
reset = 'x1b[0m'
color = eval(input('Enter something: '), {'red': red, 'reset': reset})
print(color)
Output:
Enter something: red + 'hi' + reset + 'bye'
Prints hibye
but the hi
is red and the bye
is white.
Note: eval
can be dangerous, don’t let the user enter something like __import__('shutil').rmtree('/')
– you might want to check the input before eval
uating. Adding '__builtins__': None
to the dictionary passed as the second parameter in eval
may make it a bit safer (as suggested by martineau)