【问题标题】:python propmpt-toolkit simple input coloringpython prompt-toolkit 简单输入着色
【发布时间】:2021-08-22 22:22:46
【问题描述】:

我正在尝试为将在终端中运行的某些数据库条目编写控制台应用程序。在考虑了几个 CLI 库之后,我选择了最接近我需要的 prompt-toolkit(cli 框架过于集中于命令行工具)。 Prompt-toolkit 文档规模适中,但在许多情况下未能记录简单的用例并快速跳转到高级主题。

考虑以下代码:

from prompt_toolkit import prompt, PromptSession, print_formatted_text, HTML
pts = PromptSession()
result = pts.prompt(HTML('<b>Enter some data > </b>'))

运行时显示:

输入一些数据>用户类型在这里输入

您可能会注意到提示是“粗体”的(几乎没有记录使用 HTML 进行着色提示,但我认为它可以正常工作)。我没有弄清楚的是用户输入部分的着色 - 换句话说,我想以某种简单的方式(某种颜色或效果使用户输入突出)为“用户类型输入”着色,而不使用一些词法分析器方法(已广泛记录)因为我输入的不是某种代码,而是一些简单的数据。

有人提到可以为此使用 style= 参数,但是当我尝试输入“格式字符串”时出现错误(代码如下所示):

result = pts.prompt(HTML('<b>Enter some data > </b>'), style="fg:ansiyellow bg:black bold underline")

根据https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/styling.html#styling,这应该是可接受的输入样式(据我所知)。

有什么提示吗?

【问题讨论】:

    标签: python-3.x console-application prompt-toolkit


    【解决方案1】:

    我个人在我的代码中使用了类似下面的内容。诚然,这有点 hacky,但 style= 应用于整个提示,因此需要使用 HTML 格式的字符串来覆盖它。

    prompt(HTML("<ansigray>Please enter text: </ansigray>"), style=Style.from_dict({'': 'ansired'}))
    

    这将产生如下输出:

    Please enter text: Hello
    

    “请输入文本”将是 ansigray,默认终端文本颜色,而“Hello”,用户输入,将是红色

    关于 style= 参数,需要将其实例化为带有规则字典的 Style 对象。

    我发现这里的示例非常方便: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/colored-prompt.py

    文档也是如此,其中有各种示例(尽管不是针对这种确切情况):https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#colors

    最后 ansi 颜色和样式规则记录在这里:https://python-prompt-toolkit.readthedocs.io/en/master/pages/advanced_topics/styling.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多