• python——使用readline库实现tab自动补全


    Input History

    readline tracks the input history automatically. There are two different sets of functions for working with the history. The history for the current session can be accessed with get_current_history_length()and get_history_item(). That same history can be saved to a file to be reloaded later using write_history_file() and read_history_file(). By default the entire history is saved but the maximum length of the file can be set with set_history_length(). A length of -1 means no limit.

    import readline
    import logging
    import os
    
    LOG_FILENAME = '/tmp/completer.log'
    HISTORY_FILENAME = '/tmp/completer.hist'
    
    logging.basicConfig(filename=LOG_FILENAME,
                        level=logging.DEBUG,
                        )
    
    def get_history_items():
        return [ readline.get_history_item(i)
                 for i in xrange(1, readline.get_current_history_length() + 1)
                 ]
    
    class HistoryCompleter(object):
        
        def __init__(self):
            self.matches = []
            return
    
        def complete(self, text, state):
            response = None
            if state == 0:
                history_values = get_history_items()
                logging.debug('history: %s', history_values)
                if text:
                    self.matches = sorted(h 
                                          for h in history_values 
                                          if h and h.startswith(text))
                else:
                    self.matches = []
                logging.debug('matches: %s', self.matches)
            try:
                response = self.matches[state]
            except IndexError:
                response = None
            logging.debug('complete(%s, %s) => %s', 
                          repr(text), state, repr(response))
            return response
    
    def input_loop():
        if os.path.exists(HISTORY_FILENAME):
            readline.read_history_file(HISTORY_FILENAME)
        print 'Max history file length:', readline.get_history_length()
        print 'Startup history:', get_history_items()
        try:
            while True:
                line = raw_input('Prompt ("stop" to quit): ')
                if line == 'stop':
                    break
                if line:
                    print 'Adding "%s" to the history' % line
        finally:
            print 'Final history:', get_history_items()
            readline.write_history_file(HISTORY_FILENAME)
    
    # Register our completer function
    readline.set_completer(HistoryCompleter().complete)
    
    # Use the tab key for completion
    readline.parse_and_bind('tab: complete')
    
    # Prompt the user for text
    input_loop()

    The HistoryCompleter remembers everything you type and uses those values when completing subsequent inputs.

    $ python readline_history.py
    Max history file length: -1
    Startup history: []
    Prompt ("stop" to quit): foo
    Adding "foo" to the history
    Prompt ("stop" to quit): bar
    Adding "bar" to the history
    Prompt ("stop" to quit): blah
    Adding "blah" to the history
    Prompt ("stop" to quit): b
    bar   blah
    Prompt ("stop" to quit): b
    Prompt ("stop" to quit): stop
    Final history: ['foo', 'bar', 'blah', 'stop']
    

    The log shows this output when the “b” is followed by two TABs.

    DEBUG:root:history: ['foo', 'bar', 'blah']
    DEBUG:root:matches: ['bar', 'blah']
    DEBUG:root:complete('b', 0) => 'bar'
    DEBUG:root:complete('b', 1) => 'blah'
    DEBUG:root:complete('b', 2) => None
    DEBUG:root:history: ['foo', 'bar', 'blah']
    DEBUG:root:matches: ['bar', 'blah']
    DEBUG:root:complete('b', 0) => 'bar'
    DEBUG:root:complete('b', 1) => 'blah'
    DEBUG:root:complete('b', 2) => None
    

    When the script is run the second time, all of the history is read from the file.

    $ python readline_history.py
    Max history file length: -1
    Startup history: ['foo', 'bar', 'blah', 'stop']
    Prompt ("stop" to quit):
    

    There are functions for removing individual history items and clearing the entire history, as well.

    最后效果是你输入的历史的foo被记录了下来,下次打开的时候输入fo然后tab就可以自动提示foo来补全了!

  • 相关阅读:
    Cg(C for Graphic)标准函数库之数学函数与几何函数
    小技巧总结
    MVC学习笔记
    HTML5 ajax上传附件
    JS:公历、农历互转
    JS:中文GB2312编码
    Oracle:递归查询(树形结构数据)
    oracle:自定义多行合并聚合函数
    编写一个可配置的网页信息提取组件 (二)—— 优雅的.net core 配置系统
    编写一个可配置的网页信息提取组件
  • 原文地址:https://www.cnblogs.com/bonelee/p/6184663.html
Copyright © 2020-2023  润新知