Persistent history in python cmd module

Question:

Is there any way to configure the CMD module from Python to keep a persistent history even after the interactive shell has been closed?

When I press the up and down keys I would like to access commands that were previously entered into the shell on previous occasions that I ran the python script as well as the ones I have just entered during this session.

If its any help cmd uses set_completer imported from the readline module

Asked By: PJConnol

||

Answers:

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.

Answered By: Martijn Pieters