如何在input()函数中将颜色/格式应用于显示的文本(类似于打印语句格式)? [英] How to apply coloring/formatting to the displayed text in input()-function (similar to print statement formatting)?

查看:151
本文介绍了如何在input()函数中将颜色/格式应用于显示的文本(类似于打印语句格式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的游戏应用程序,它是从Windows控制台(cmd.exe)启动的.我可以使用ANSI转义序列以任何所需的方式格式化文本.

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.

我也很想对input()方法中的文本应用格式设置,但是我还没有找到一种方法.这是测试代码...

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

在我的Windows控制台中,您将看到ANSI序列在输入语句中显示为简单字符串:

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

在我的Spyder IDE控制台中,它具有相反的效果:

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

有人可以向我解释在不同控制台中显示的行为吗? 在Windows cmd控制台中,有什么方法可以格式化input()-文本?这是我的程序正常运行的地方,我想使其更漂亮:-)

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

提前谢谢!

推荐答案

colorama通过替换sys.stderr 的版本解释ISO 6429序列,进行适当的Win32调用以实现它们,并将其余字符发送到基础流上.这解释了您的观察:input不使用Python级别的sys.stdout.write,Spyder解释序列本身,但不受Win32调用的影响.

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.

唯一合理的解决方法似乎是在没有提示的情况下使用input.您只需在提示符下print且没有换行符(在Python  2中​​以,结尾或在Python  3中以end=""结尾)即可.

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

这篇关于如何在input()函数中将颜色/格式应用于显示的文本(类似于打印语句格式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆