Persistent history in python cmd module
<p>Is there any way to configure the <a href="https://docs.python.org/2/library/cmd.html" rel="nofollow">CMD module from Python</a> to keep a persistent history even after the interactive shell has been closed?</p>

<p>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.</p>

<p>If its any help cmd uses <code>set_completer</code> imported from the <a href="https://docs.python.org/2/library/readline.html" rel="nofollow">readline module</a></p>

<p><code>readline</code> automatically keeps a history of everything you enter. All you need to add is hooks to load and store that history.</p>

<p>Use <a href="https://docs.python.org/2/library/readline.html#readline.read_history_file" rel="nofollow"><code>readline.read_history_file(filename)</code></a> to read a history file. Use <a href="https://docs.python.org/2/library/readline.html#readline.write_history_file" rel="nofollow"><code>readline.write_history_file()</code></a> to tell <code>readline</code> to persist the history so far. You may want to use <a href="https://docs.python.org/2/library/readline.html#readline.set_history_length" rel="nofollow"><code>readline.set_history_length()</code></a> to keep this file from growing without bound:</p>

<pre><code>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)
</code></pre>

<p>I used the <a href="https://docs.python.org/2/library/cmd.html#cmd.Cmd.preloop" rel="nofollow"><code>Cmd.preloop()</code></a> and <a href="https://docs.python.org/2/library/cmd.html#cmd.Cmd.postloop" rel="nofollow"><code>Cmd.postloop()</code></a> hooks to trigger loading and saving to the points where the command loop starts and ends.</p>

<p>If you don't have <code>readline</code> installed, you could simulate this still by adding a <a href="https://docs.python.org/2/library/cmd.html#cmd.Cmd.precmd" rel="nofollow"><code>precmd()</code> method</a> and record the entered commands yourself.</p>

python readline python-module python-cmd