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来补全了!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」