有没有办法配置CMD module from Python以便在交互式shell关闭后保留持久历史记录?
当我按下向上和向下键时,我想访问先前在我运行python脚本以及我刚刚在此会话期间输入的脚本时先输入shell的命令。
如果任何帮助cmd使用从readline module
导入的set_completer
答案 0 :(得分:11)
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来模拟此项并自行记录输入的命令。