0
Pythonコードを実行するPythonテーマを開発したいと思います。ユーザーがテキストを入力している間にinput()のトークンを色づけします。pylinesをreadlineで使用して、入力テキストをトークンに従って色づける方法は?
最近、私はreadlineとpygmentsを学び始めました。
キーワードのトークンをタブ補完に追加できます。また、私は、機能を強調表示してstdoutテキストを着色することができます。
しかし、私はまだ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回押すとキーワードが表示されます。
ありがとうございます。