猿问

Python:正确使用set_completion_display_matches_hook

我正在尝试编写一个函数来在用户按下Tab键时显示自定义视图。显然,“ set_completion_display_matches_hook”功能是我所需要的,我可以显示一个自定义视图,但问题是我必须按Enter才能再次获得提示。


Python2中的解决方案似乎就是这样(此处的解决方案):


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()

有什么想法吗?


慕的地10843
浏览 209回答 3
3回答

沧海一幻觉

首先,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()

Cats萌萌

这个为我工作,用于重新显示替换,并且显示python3的比赛结束:    def match_display_hook(self, substitution, matches, longest_match_length):        print("")        for match in matches:            print(match)        print("")        sys.stdout.write(substitution)        sys.stdout.flush()        return None而以前使用打印提示的用户则没有。(没有找到问题的根源)
随时随地看视频慕课网APP

相关分类

Python
我要回答