问题
I want to develop a Python theme which executes Python codes and which colorize the tokens in input() while users typing some text.
Recently I have started to learn readline and pygments.
I can add keyword tokens to the tab completion. Also i can colorize the stdout text with pygments highlight function.
But still i can't colorize the tokens in input().
Is there anyone to give me an idea to do what i want?
The codes below are from an example application.
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)
And this is the screenshot of how this application works. As you can see, when the program starts, a "print('hello world')" string is highlighted with pygments. And after that pressing the TAB 2 times gives the keywords.
Thanks in advance.
回答1:
The problem is solved with the below codes:
from pygments.lexers import Python3Lexer
from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.layout.lexers import PygmentsLexer
text = prompt('>>> ', lexer=PygmentsLexer(Python3Lexer))
来源:https://stackoverflow.com/questions/46812451/how-to-use-pygments-with-readline-to-colorize-the-input-text-according-to-the-to