如何使用带有 readline 的 pygments 根据标记为输入文本着色?

How to use pygments with readline to colorize the input text according to the tokens?

我想开发一个 Python 主题,它执行 Python 代码并在用户输入一些文本时为 input() 中的标记着色。

最近开始学习readline和pygments

我可以将关键字标记添加到选项卡完成中。我还可以使用 pygments 高亮功能为标准输出文本着色。

但我仍然无法为 input() 中的标记着色。

有没有人给我一个想法,让我做我想做的事?

以下代码来自示例应用程序。

import readline
from pygments.token import Token
from pygments.style import Style
from pygments.lexers import Python3Lexer
from pygments import highlight
from pygments.formatters import Terminal256Formatter
import keyword


class Completer:
    def __init__(self, words):
        self.words = words
        self.prefix = None
        self.match = None

    def complete(self, prefix, index):
        if prefix != self.prefix:
            self.match = [i for i in self.words if i.startswith(prefix)]
            self.prefix = prefix
        try:
            return self.match[index]
        except IndexError:
            return None


class MyStyle(Style):
    styles = {
        Token.String: '#ansiwhite',
        Token.Number: '#ansired',
        Token.Keyword: '#ansiyellow',
        Token.Operator: '#ansiyellow',
        Token.Name.Builtin: '#ansiblue',
        Token.Literal.String.Single: '#ansired',
        Token.Punctuation: '#ansiwhite'
    }


if __name__ == "__main__":
    code = highlight("print('hello world')", Python3Lexer(), Terminal256Formatter(style=MyStyle))
    readline.parse_and_bind('tab: complete')
    readline.set_completer(Completer(keyword.kwlist).complete)
    print(code)
    while True:
        _input = input(">>> ")
        if _input == "quit":
            break
        else:
            print(_input)

这是此应用程序工作原理的屏幕截图。可以看到,程序启动时,用pygments高亮了一个"print('hello world')"字符串。然后按两次 TAB 给出关键字。

提前致谢。

问题已通过以下代码解决:

from pygments.lexers import Python3Lexer
from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.layout.lexers import PygmentsLexer
text = prompt('>>> ', lexer=PygmentsLexer(Python3Lexer))