How to apply coloring/formatting to the displayed text in input()-function (similar to print statement formatting)?
Asked Answered
B

1

6

I have a small game application, which is started from the Windows console (cmd.exe). I am able to format the text in any desired way using ANSI escape sequences.

I would also love to apply formatting to the text from the input()-method, but I have not found a way how to do so. Here is the testing code...

from colorama import init
init(autoreset=True)

RED = "\x1b[1;31;40m"

print(f"{RED}This text is red\n")

not_red = input(f"{RED}Insert some random stuff: ")

in my windows console, you will see that the ANSI sequence is displayed as a simple string in the input statement:

enter image description here

whereas in my Spyder IDE console, it has the reverse effect:

enter image description here

Can anyone explain the displayed behaviour in the different consoles to me? And is there any way to format the input()-text in the Windows cmd console? This is where my program is run normally and I would like to make it even prettier :-)

Thanks in advance!

Bleat answered 30/8, 2018 at 17:6 Comment(3)
Please take a look at this question unfortunately I cannot flag as a duplicate due to the open bountyCornela
ANSI codes work directly with input in OSX (tested in jupyter notebook, python 3.6)Agapanthus
interesting link, I'll take a look. thanks a lot!Bleat
U
3

colorama works by replacing sys.stdout and sys.stderr with versions that interpret ISO 6429 sequences, make appropriate Win32 calls to implement them, and send the rest of the characters on to the underlying stream. This explains your observations: input doesn’t use the Python-level sys.stdout.write, and Spyder interprets the sequences itself but is unaffected by the Win32 calls.

The only reasonable fix seems to be to use input with no prompt; you shouldn’t need to do any more than print your prompt with no newline (a trailing , in Python 2 or end="" in Python 3).

Uhhuh answered 2/9, 2018 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.