Persistent history in python cmd module
Asked Answered
P

1

9

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

Pampa answered 14/9, 2016 at 16:4 Comment(0)
B
23

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.

Baht answered 14/9, 2016 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.