2013-05-15 28 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()