【问题标题】:How to use pygments with readline to colorize the input text according to the tokens?如何使用带有 readline 的 pygments 根据标记为输入文本着色?
【发布时间】:2017-10-18 14:21:12
【问题描述】:

我想开发一个 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)

这是此应用程序如何工作的屏幕截图。如您所见,当程序启动时,“print('hello world')”字符串用 pygments 突出显示。然后按 TAB 2 次给出关键字。

提前致谢。

【问题讨论】:

    标签: python readline pygments


    【解决方案1】:

    问题通过以下代码解决:

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

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多