2013-05-15 29 views
2

我試圖編寫一個函數來顯示用戶按下Tab鍵時的自定義視圖。顯然,「set_completion_display_matches_hook」函數是我需要的,我可以顯示一個自定義視圖,但問題是我必須按Enter才能再次獲得提示。Python:正確使用set_completion_display_matches_hook

在Python2的解決方案似乎是(solution here):

def match_display_hook(self, substitution, matches, longest_match_length): 
    print '' 
    for match in matches: 
     print match 
    print self.prompt.rstrip(), 
    print readline.get_line_buffer(), 
    readline.redisplay() 

但它不與Python3工作。我做了這些語法修改:

def match_display_hook(self, substitution, matches, longest_match_length): 
     print('\n----------------------------------------------\n') 
     for match in matches: 
      print(match) 
     print(self.prompt.rstrip() + readline.get_line_buffer()) 
     readline.redisplay() 

有什麼想法嗎?

回答

0

首先,Python 2代碼使用逗號使線條未完成。在Python 3,它使用end關鍵字完成:

print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='') 

然後,沖洗需要實際顯示未完成的線(由於線緩衝):

sys.stdout.flush() 

redisplay()呼叫似乎並不被需要。

最終代碼:

def match_display_hook(self, substitution, matches, longest_match_length): 
    print() 
    for match in matches: 
     print(match) 
    print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='') 
    sys.stdout.flush()