Python 自動補完プログラム

Python で対話プログラムを自作した場合などで、タブで補完したい場合がある。

今回はその方法について説明する。


>>> import readline
>>>
>>> # 補完する文字列のリスト
>>> wordList = ['apple', 'bitcoin', 'coop']
>>>
>>> # 入力補完を行う関数
>>> def completer(text, state):
...     options = [x for x in wordList if x.startswith(text)]
...     try:
...         return options[state]
...     except IndexError:
...         return None
... 
>>> 
>>> #入力補完を行う関数を登録
>>> readline.set_completer(completer)
>>> 
>>> # タブで補完を行う
>>> readline.parse_and_bind("tab: complete")
>>> 
>>> # 内部的に readline() を利用している関数であれば何でも良い
>>> # キーボード入力
>>> input()
apple        ← 「a」を入力した後に「Tab」キーを押した
'apple'
>>> 


参考

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です