使用命令行调试 Rscript

5

我想知道有没有人知道如何在Linux环境下使用命令行调试R脚本。例如,在Python中,我们可以使用pdb。我们首先设置断点(pdb.set_trace()),然后可以使用像“c”,“n”,“s”,“b”等命令来调试Linux环境中的Python代码。我已经搜索了很多关于R调试的信息,但迄今为止我没有在R中找到类似的功能。非常感谢您的帮助!


当你说“命令行”时,是指你通过类似于Rscript file.R的方式运行脚本,还是指你从R内部调用source()函数? - joran
1
如果是前者(Rscript),我认为不幸的是答案是 cat(或 messagewarning 或某种形式的日志记录)。如果在 R 控制台(Rterm、RStudio 或类似工具)中,则可以参考 http://adv-r.had.co.nz/Exceptions-Debugging.html。 - r2evans
@joran,我是说使用 Rscript file.R。 - Tong Qiu
@r2evans,谢谢,让我看一下。 - Tong Qiu
1
如果您通常使用 Rscript,那么与之等价的 "pdb" 就是 R。 R 的调试支持“还好”,但不如 pdbgdb 或许多编程语言/环境提供的调试技术水平。 - r2evans
也许 http://www.math.ncu.edu.tw/~chenwc/R_note/reference/debug/Rdebug.pdf 会有所帮助。 - zhaofeng-shu33
1个回答

0

在命令行中没有本地调试Rscript的方法,但是您可以使用我用readLineseval编写的一种hacky解决方法。

ipdb.r <- function(){
  input <- ""
  while(!input %in% c("c","cont","continue"))
  {
    cat("ipdb.r>")
    # stdin connection to work outside interactive session
    input <- readLines("stdin",n=1)
    if(!input %in% c("c","cont","continue","exit"))
    {
      # parent.frame() runs command outside function environment
      print(eval(parse(text=input),parent.frame()))
    }else if(input=="exit")
    {
      stop("Exiting from ipdb.r...")
    }
  }
}

在R文件中的示例用法,可通过Rscript调用:

ipdbrtest.R

a <- 3
print(a)
ipdb.r()
print(a)

命令行:

$ Rscript ipdbrtest.R
[1] 3
ipdb.r>a+3
[1] 6
ipdb.r>a+4
[1] 7
ipdb.r>a <- 4
[1] 4
ipdb.r>c
[1] 4

我鼓励任何使用这个的人扩展它以获得更强大的调试功能。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接