【问题标题】:Access/manipulate history stack in R (up/down arrow)在 R 中访问/操作历史堆栈(向上/向下箭头)
【发布时间】:2014-12-17 05:53:25
【问题描述】:

我正在 R 中开发一个类似于 shell 的小交互式工具,它使用 readline 来提示标准输入,如下所示:

console <- function(){
  while(nchar(input <- readline(">>> "))) {
    message("You typed: ", input)
  }
}

它有效,但唯一困扰我的是,以这种方式输入的行不会被推入历史堆栈。按 R 中的向上箭头会给出在启动控制台之前输入的最后一个 R 命令。

有什么方法可以手动将input 行推送到历史堆栈上,这样按向上箭头将显示在控制台函数中输入的最新行?

【问题讨论】:

  • ?history 只是一个文本文件,您可以从脚本中写入。
  • 我认为这不是真的。它存在于内存中,仅在 R 会话结束时保存。我很确定向上箭头不会查询 txt 文件。
  • 查看savehistory的代码:function (file = ".Rhistory") invisible(.External2(C_savehistory, file))。我认为您足够精明,可以找到底层源代码。 Unix-likes 与 Windoze 的机制不同。
  • 刚刚测试过这个。如果你输入savehistory(file="newfile"),编辑文本文件添加一些新行,然后输入loadhistory(file="newfile") 并点击,你会得到刚刚添加的行。
  • 好的,谢谢,我现在知道了。我应该将每一行写入一个文本文件并在每个命令后调用loadhistory。想要添加答案?

标签: r shell console stdin


【解决方案1】:

我在rite 中使用它来将命令添加到命令历史记录中。本质上,您可以从本地文件中获取savehistoryloadhistory。我愿意:

tmphistory <- tempfile()
savehistory(tmphistory)
histcon <- file(tmphistory, open="a")
writeLines(code, histcon)
close(histcon)
loadhistory(tmphistory)
unlink(tmphistory)

注意:Mac doesn't use history in the same way as other OS's,所以要小心。

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 2013-08-18
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    相关资源
    最近更新 更多