14.3.4 输入历史
readline会自动跟踪输入历史。有两组不同的函数来处理历史。当前会话的历史可以使用get_current_history_length()和get_history_item()访问。这个历史可以保存到一个文件中,以后分别用write_history_file()和read_history_file()重新加载。默认地会保存整个历史,不过可以用set_history_length()设置文件的最大长度。如果值为-1,则表示长度没有限制。
try:
import gnureadline as readline
except ImportError:
import readline
import logging
import os
LOG_FILENAME = '/tmp/completer.log'
HISTORY_FILENAME = '/tmp/completer.hist'
logging.basicConfig(
format='%(message)s',
filename=LOG_FILENAME,
level=logging.DEBUG,
)
def get_history_items():
num_items = readline.get_current_history_length() + 1
return [
readline.get_history_item(i)
for i in range(1,num_items)
]
class HistoryCompleter:
def __init__(self):
self.matches = []
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 = input('Prompt ("stop" to quit): ')
if line == 'stop':
break
if line:
print('Adding {!r} to the history'.format(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()
HistoryCompleter记住键入的所有内容,并在完成后续输入时使用这些值。
按下b后再按下两次tab,日志会显示以下输出。
第二次运行脚本时,将从文件读取所有历史。
还有一些函数可以删除单个历史项,也可以清除整个历史。