readline模块定义了许多函数,以便于从Python解释器完成和读取/写入历史文件。此模块可以直接使用,或通过rlcompleter模块,它支持在交互式提示符处完成Python标识符。使用此模块进行的设置会影响解释器的交互式提示和由raw_input()和input()内置函数提供的提示的行为。
import os
import readline
import atexit
# readline.parse_and_bind(string)
# 执行string参数中提供的init行
readline.parse_and_bind('tab: complete')
def tab_completer(text, state):
options = [cmd for cmd in cmds if cmd.startswith(text)]
if state < len(options):
return options[state]
else:
return None
# readline.set_completer([function])
# 设置或删除完成器功能。如果指定了函数,它将被用作新的完成函数;如果省略或无,则已安装的任何完成器函数都将被删除。 completionter函数被称为函数(文本,状态),用于0,1,2,...中的
状态,直到返回非字符串值。它应该返回下一个可能的完成从文本开始。
readline.set_completer(tab_completer)
histfile = '/root/.xx_history'
if not os.path.exists(histfile) :
os.system('touch %s' % histfile)
# readline.read_history_file([filename])
# 加载阅读历史记录文件,并将其附加到历史记录列表。默认文件名为〜/ .history。这会在底层库中调用read_history()。
readline.read_history_file(histfile)
# readline.set_history_length(length)
# 设置或返回要保存在历史记录文件中的所需行数。 write_history_file()函数使用此值截断历史记录文件,方法是调用底层库中的history_truncate_file()。负值意味着无限的历史文件大小。
readline.set_history_length(1000)
# readline.write_history_file([filename])
# 将历史记录列表保存到阅读历史记录文件,覆盖任何现有文件。默认文件名为〜/ .history。这会在底层库中调用write_history()。
atexit.register(readline.write_history_file, histfile)
来自:https://docs.python.org/2/library/readline.html