python cmd 模块中的持久历史记录

Persistent history in python cmd module

是否有任何方法可以配置 CMD module from Python 以在交互式 shell 关闭后保持持久的历史记录?

当我按下向上键和向下键时,我想访问以前在 运行 python 脚本以及 shell 中输入的命令我刚刚在 session.

期间输入的那些

如果它的任何帮助 cmd 使用从 readline module

导入的 set_completer

readline 自动保留您输入的所有内容的历史记录。您需要添加的只是用于加载和存储该历史记录的挂钩。

使用 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() 防止此文件无限增长:

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)

我使用 Cmd.preloop() and Cmd.postloop() 挂钩触发加载和保存到命令循环开始和结束的点。

如果你没有安装readline,你仍然可以通过添加一个precmd() method来模拟这个,并自己记录输入的命令。