R:Sink(type=“message”) 用于错误报告 - 我可以获取行号吗?

R: Sink(type="message") for error reporting - can I get a line number?

提问人:Keegan Smith 提问时间:11/26/2016 更新时间:11/26/2016 访问量:2066

问:

TL的;DR:我正在使用 sink() 在脚本运行期间记录错误,并将它们保存到可以在运行后查看的数据帧中,以突出显示错误。如果可能的话,我想要一种方法来包含错误行号。

'

长版本:我正在编写一个 R 脚本来处理国家天气数据集,这些数据集有时包含异常 - 缺少数据、意外符号等。数据中的不一致可能会导致脚本中的错误,这对我作为程序员来说很好 - 我可以识别并修复它们。然而,我的最终目标是让它广泛适用于任何国家天气数据集——这意味着它可能被对 R 知识知之甚少的人使用。该脚本目前有 ~700 行长,并且会变得更长,其中包含许多用户定义的函数。这使得查看控制台历史记录变得相当乏味,尤其是对于新手 R 用户而言。

到目前为止,我的解决方案是将脚本运行期间生成的所有错误和警告消息保存到表中,这将是用户在运行后看到的第一件事,迫使他们承认错误。我正在使用 sink() 函数(我在另一个 SO 帖子中找到了该方法,在下面的代码注释中归因),它工作得很好,只是我想不出一种方法来记录错误消息的行号。Traceback() 在这种情况下不起作用,因为我想要所有错误,而不仅仅是堆栈中最近的错误。

如前所述,我的代码如下。我主要在 RStudio 中工作,所以我通过将块粘贴到控制台中来运行它。

 # Method accesed online Nov 24, 2016, at:
 # http://stackoverflow.com/questions/11666086/output-error-warning-log-txt-file-when-running-r-script-under-command-line
 setwd(tempdir()) # tempdir() creates names for temporary files

 # Capture messages and errors to a file
 zz=file("all.Rout",open="wt") # file() creates a file connection and opens it 
                               #  in wt="write text mode".
 sink(zz,type="message") # sink diverts R output to a connection - in this case, the error log, zz

 # test out some error samples (4)
 try(log("a")) # try runs an expression and allows user code to handle error-recovery
 z x a # try() is not necessary - any error will be flagged and entered to the log
 mean()
 sds(42)

 # Display log file
 readLines("all.Rout")
 error.log=data.frame(readLines("all.Rout")) # write these to an error log DF

 # Reset sink, close connection
 sink(type="message") # this prevents diversion of messages -
                      # they will now appear in console, as default
 close(zz) # close the error log connection
 remove(zz) # blank from mem

 # OK, this is good - but can I get line numbers to output to the DF?

谁能推荐一种使用 sink() 使其工作的方法?

或者,如果您知道其他方法可以访问我想要的输出(错误/警告消息的列表/表及其在代码中的位置),我会全神贯注。

r 处理 错误 报告 行号 接收器

评论

0赞 IRTFM 11/26/2016
我不认为这可以说明捕获“行号”,因为在控制台输入期间确实没有行号。我知道的行号是在脚本解析期间构造的。看。该页面还建议考虑将?parse?tracebackoptions(error = function() traceback(2))
0赞 Keegan Smith 11/26/2016
谢谢 - 我想没有办法在交互模式下追溯识别错误的位置,那么?将我的错误选项设置为 traceback(2) 会在错误发生时打印堆栈,但此打印不会被 sink() 捕获,因此基本上是相同的问题 - 错误在交互模式下突出显示,现在是调用堆栈而不是错误消息。sink() 中不会产生任何新信息。我必须更多地了解 source()。似乎这是运行代码并返回行号的唯一方法,就像您在 parse() 上的注释一样。
0赞 3pitt 1/24/2018
要解决 sink,为什么不注释掉所有 sink 命令和等效的 main,输入 R 会话/shell,获取文件,然后运行它?这样,您可以设置选项并使用回溯
0赞 Keegan Smith 1/25/2018
@MikePalmice - 你已经解决了这里的主要问题;这种错误报告方法在以交互方式运行代码时不起作用。对于这样的事情,无论如何我都应该采购脚本,在这种情况下,错误回溯有效。

答: 暂无答案