问题
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:
whereas in my Spyder IDE console, it has the reverse effect:
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!
回答1:
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).
来源:https://stackoverflow.com/questions/52102240/how-to-apply-coloring-formatting-to-the-displayed-text-in-input-function-simi