美文网首页
readline自动补全功能

readline自动补全功能

作者: ThomasYoungK | 来源:发表于2018-12-30 16:53 被阅读28次

    用python可以模拟命令行的自动补全功能,其中mac电脑还有些小区别,都记录在下面了,用的是标准库的readline模块:

    import readline
    import rlcompleter
    
    def make_completer(vocabulary):
        def custom_complete(text, state):
            # None is returned for the end of the completion session.
            results = [x for x in vocabulary if x.startswith(text)] + [None]
            # A space is added to the completion since the Python readline doesn't
            # do this on its own. When a word is fully completed we want to mimic
            # the default readline library behavior of adding a space after it.
            return results[state] + " "
    
        return custom_complete
    
    
    def main():
        vocabulary = {'cat', 'dog', 'canary', 'cow', 'hamster'}
        if 'libedit' in readline.__doc__:  # mac OS/X 是走这个分支
            print('x')
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")
        readline.set_completer(make_completer(vocabulary))
    
        try:
            while True:
                s = input('>> ').strip()
                print('[{0}]'.format(s))
        except (EOFError, KeyboardInterrupt) as e:
            print('\nShutting down...')
    
    
    if __name__ == '__main__':
        main()
    
    

    相关文章

      网友评论

          本文标题:readline自动补全功能

          本文链接:https://www.haomeiwen.com/subject/vsivlqtx.html