[英]How to make python autocompletion display matches?
我有一個具有自動完成功能的完成者類。 簡單版本:
class Completer:
def __init__(self):
self.words = ["mkdir","mktbl", "help"]
self.prefix = None
def complete(self, prefix, index):
if prefix != self.prefix:
self.matching_words = [w for w in self.words if w.startswith(prefix)]
self.prefix = prefix
else:
pass
try:
return self.matching_words[index]
except IndexError:
return None
並執行類似這樣的操作以使用readline進行自動完成:
import readline
readline.parse_and_bind("tab: complete")
completer = Completer()
readline.set_completer(completer.complete)
user_input =raw_input("> ")
因此,在示例中有3個單詞用於自動完成[“ help ”,“ mkdir ”,“ mktbl ”]。
如果用戶執行:
> he<tab>
用戶得到:
> help
但如果用戶執行
> mk<tab>
沒有任何事情發生,因為沒有一個匹配(mkdir和mktbl)
如果有多個匹配項,如何顯示選項? 像Bash一樣使用文件名自動完成?
因此,用戶可以獲得如下內容:
> mk<tab>
mktbl mkdir
> mk<cursor>
PS我試過試試
_readline.insert_text(...)_
和
打印...
進入完成函數,但它剎車插入,所以用戶得到這樣的東西:
> mk<tab>
> mkmktbl mkdir <cursor>
PPS我需要一個linux解決方案。
設置readline選項
set show-all-if-ambiguous on
如果你想在第一個<tab>
之后完成。 否則只需按兩次<tab>
。
參考: http : //caliban.org/bash/,Section readline提示和技巧
PS。 在OS X和Linux上測試了你的代碼,它運行良好(在我的機器上;)
我被建議一個完整答案的解決方案。 它允許組織自動完成選項的完成輸出。
對於linux readline,有函數readline.set_completion_display_matches_hook
http://docs.python.org/library/readline.html?highlight=readline#readline.set_completion_display_matches_hook
因此,對於上面列出的示例,此代碼
def print_suggestions(self, substitution, matches, longest_match_length) :
print "useless text to be displayed"
print substitution
print " ".join[match for match in matches]
print longest_match_length
readline.set_completion_display_matches_hook(print_suggestions)
這將產生:
> mk<tab>
useless text to be displayed
mk
mkdir mktbl
5
> mk<cursor>
對於Windows readline,堆棧溢出有一個答案:
如何讓IPython按類組織標簽完成的可能性?
不知道它對mac的作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.