readline
automatically keeps a history of everything you enter. All you need to add is hooks to load and store that history.
Use readline.read_history_file(filename)
to read a history file. Use readline.write_history_file()
to tell readline
to persist the history so far. You may want to use readline.set_history_length()
to keep this file from growing without bound:
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)
I used the Cmd.preloop()
and Cmd.postloop()
hooks to trigger loading and saving to the points where the command loop starts and ends.
If you don't have readline
installed, you could simulate this still by adding a precmd()
method and record the entered commands yourself.