为了账号安全,请及时绑定邮箱和手机立即绑定

Python:正确使用set_completion_display_matches_hook

Python:正确使用set_completion_display_matches_hook

慕的地10843 2021-03-20 14:15:14
我正在尝试编写一个函数来在用户按下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()有什么想法吗?
查看完整描述

3 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

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


查看完整回答
反对 回复 2021-03-24
?
Cats萌萌

TA贡献1805条经验 获得超9个赞

这个为我工作,用于重新显示替换,并且显示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

而以前使用打印提示的用户则没有。(没有找到问题的根源)


查看完整回答
反对 回复 2021-03-24
  • 3 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号