繁体   English   中英

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()来保持此文件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()Cmd.postloop()挂钩来触发加载并保存到命令循环开始和结束的点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM