You need to enable JavaScript to run this app. 如何在Python中为命令行工具的用户输入内容添加着色效果?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中为命令行工具的用户输入内容添加着色效果?

实现方案

你可以直接使用Python生态的prompt_toolkit库完成需求,它是专门用于构建现代化命令行交互界面的成熟工具,内置了输入捕获、光标控制、实时渲染、快捷键支持等所有底层能力,你只需要关注自己的格式化逻辑即可,不需要从零编写交互底层代码。

基础使用步骤

  • 安装依赖:pip install prompt_toolkit
  • 你仅需实现自己的输入格式化/语法高亮逻辑,剩下的交互行为都由库默认处理,示例代码如下:
from prompt_toolkit import prompt
from prompt_toolkit.lexers import Lexer
from prompt_toolkit.styles import Style

# 自定义语法高亮器,实现你要的格式化逻辑
class CalculatorLexer(Lexer):
    def lex_document(self, document):
        def get_line(lineno):
            text = document.lines[lineno]
            formatted = []
            # 这里替换为你自己的colourFormatInput逻辑
            for char in text:
                if char.isdigit():
                    # 数字标注为红色
                    formatted.append(("class:digit", char))
                elif char in "+-*/()=":
                    # 运算符标注为蓝色
                    formatted.append(("class:operator", char))
                else:
                    formatted.append(("class:text", char))
            return formatted
        return get_line

# 自定义样式规则
custom_style = Style([
    ("digit", "#ff0000 bold"),
    ("operator", "#0000ff bold"),
    ("text", "#ffffff"),
])

if __name__ == "__main__":
    while True:
        # 启动交互式输入,实时渲染格式化效果
        input_content = prompt(
            "calc> ",
            lexer=CalculatorLexer(),
            style=custom_style
        )
        # 回车后执行你的计算逻辑即可
        if input_content.strip() in ("exit", "quit", "q"):
            break
        # 注意:不要直接使用eval处理用户输入,存在安全风险,替换为你自己的计算逻辑
        print(f"结果:{eval(input_content)}")

额外支持的能力

无需额外编码,你就可以默认获得这些交互能力:

  • 方向键移动光标、任意位置插入/删除内容
  • 上下键调取历史输入记录
  • 鼠标点击移动光标(可选开启)
  • 常用快捷键支持(Ctrl+A跳转到行首、Ctrl+U清空整行等)

如果你的需求更简单,也可以选择标准库自带的curses模块做开发,不过需要你自己实现的逻辑会比prompt_toolkit多不少,优先推荐前者。


内容的提问来源于stack exchange,提问作者Maddy Guthridge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 04:27:01