【问题标题】:Persistent history in python cmd modulepython cmd模块中的持久历史记录
【发布时间】:2017-01-22 12:43:50
【问题描述】:
【问题讨论】:
标签:
python
readline
python-module
python-cmd
【解决方案1】:
readline 自动保存您输入的所有内容的历史记录。您需要添加的只是加载和存储该历史记录的挂钩。
使用readline.read_history_file(filename) 读取历史文件。使用readline.write_history_file() 告诉readline 保留迄今为止的历史记录。您可能想使用readline.set_history_length() 来防止此文件无限制地增长:
import os.path
try:
import readline
except ImportError:
readline = None
histfile = os.path.expanduser('~/.someconsole_history')
histfile_size = 1000
class SomeConsole(cmd.Cmd):
def preloop(self):
if readline and os.path.exists(histfile):
readline.read_history_file(histfile)
def postloop(self):
if readline:
readline.set_history_length(histfile_size)
readline.write_history_file(histfile)
我使用Cmd.preloop() 和Cmd.postloop() 挂钩触发加载和保存到命令循环开始和结束的点。
如果您没有安装readline,您仍然可以通过添加precmd() method 来模拟这种情况,并自己记录输入的命令。