【问题标题】:Persistent history in python cmd modulepython cmd模块中的持久历史记录
【发布时间】:2017-01-22 12:43:50
【问题描述】:

有没有什么方法可以配置CMD module from Python,即使在交互式外壳关闭后也能保持持久的历史记录?

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

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

【问题讨论】:

    标签: python readline python-module python-cmd


    【解决方案1】:

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

    使用readline.read_history_file(filename) 读取历史文件。使用readline.write_history_file() 告诉readline 保留迄今为止的历史记录。您可能想使用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() method 来模拟这种情况,并自己记录输入的命令。

    【讨论】:

      猜你喜欢
      • 2013-05-04
      • 1970-01-01
      • 2021-05-27
      • 2011-01-24
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多