【发布时间】: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 次给出关键字。
提前致谢。
【问题讨论】: