gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:06 25 4
gpt4 key购买 nike

有没有办法配置 CMD module from Python即使在交互式 shell 关闭后也能保持持久的历史记录?

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

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

最佳答案

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

使用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()钩子(Hook)触发加载和保存到命令循环开始和结束的点。

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

关于python - python cmd 模块中的持久历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39495024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com