关于readline:python cmd模块中的永久历史记录

Persistent history in python cmd module

是否有任何方法可以从Python配置CMD模块以保持持久的历史记录,即使在关闭交互式shell之后也是如此?

当我按下向上和向下键时,我想访问以前在运行python脚本以及在本次会议中刚刚输入的命令之前输入到shell中的命令。

如果其任何帮助cmd使用从readline模块导入的set_completer


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

使用readline.read_history_file(filename)读取历史文件。使用readline.write_history_file()告诉readline保留到目前为止的历史记录。您可能要使用readline.set_history_length()来防止该文件无限制地增长:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()Cmd.postloop()钩子触发加载并保存到命令循环开始和结束的点。

如果没有安装readline,则可以通过添加precmd()方法并自己记录输入的命令来模拟此情况。