zoukankan      html  css  js  c++  java
  • 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来补全了!

  • 相关阅读:
    Informix IDS 11系统办理(918考试)认证指南,第6部分:IDS备份和恢复(1)
    Informix IDS 11体系处置(918检验)认证指南,第 4 局部: 性能调优(7)
    我常用网址整理
    System.Insert 插入字符串
    System.Length 获取字符串或数组的长度
    System.New、System.Dispose 为某个指针申请和释放内存
    System.GetMem、System.FreeMem 申请和释放内存
    学习 TList 类的实现[1]
    学习 TList 类的实现[2]
    System.ReallocMem 重新申请内存
  • 原文地址:https://www.cnblogs.com/bonelee/p/6184663.html
Copyright © 2011-2022 走看看