Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 366
Cut7er Avatar asked Aug 30 '18 17:08

Cut7er


People also ask

How to set the color of the text?

The color property is used to set the color of the text. The color is specified by: a color name - like "red" a HEX value - like "#ff0000" an RGB value - like "rgb(255,0,0)"

Which property is used to set text color?

Text Color The color property is used to set the color of the text. The color is specified by: a color name - like "red"

What is text formatting in CSS?

So far, we have studied about text formatting ways in CSS. You could see the text is presented with different types of text formatting properties. These properties are very important aspects of CSS to display the text on the web page so that users or readers can get attract by seeing your text on the website.

What determines the color of a color?

The color is specified by: 1 a color name - like "red" 2 a HEX value - like " 3 ff0000" 4 an RGB value - like "rgb (255,0,0)" More ...


1 Answers

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).

like image 113
Davis Herring Avatar answered Oct 17 '22 20:10

Davis Herring