PJC*_*nol 4 python python-module readline python-cmd
是否有任何方法可以从Python配置CMD模块,即使在交互式shell关闭后仍保留持久历史记录?
当我按下向上和向下键时,我想访问先前在我运行python脚本以及我刚刚在此会话期间输入的脚本时先前输入shell的命令.
如果其任何帮助cmd使用set_completer从readline模块导入
Mar*_*ers 12
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)
Run Code Online (Sandbox Code Playgroud)
我使用Cmd.preloop()和Cmd.postloop()钩子来触发加载并保存到命令循环开始和结束的点.
如果您尚未readline安装,则可以通过添加precmd()方法并自行记录输入的命令来模拟此操作.