2014-09-11 45 views
5

我写了一个R消息,它将消息(进度报告)写入文本文件。我修改了error选项,以便在发生错误时,该错误消息也将写入该文件:停止R脚本而不会在“包装过程中发生错误”消息

options(error = function() { 
cat(geterrmessage(),file = normalizePath("logs/messages.txt"),append = TRUE) 
stop() 
}) 

它的工作原理,但如果确实发生了错误,我得到的控制台/终端窗口此消息:

Error during wrapup: 
Execution halted 

所以我想有一个更好的方法来中断脚本的执行......还是有?

+0

我怀疑你必须从中删除'stop()'。 – Andrie 2014-09-11 08:05:20

+0

然后会发生什么情况是,如果我使用Rscript.exe myscript.R运行脚本,则会报告错误,但脚本不会停止。 – 2014-09-12 23:09:51

+0

尝试使用q()而不是stop()。错误处理程序会使用stop()函数调用,所以在stop内停止......听起来像递归。这*可能是错的。 – 2014-11-21 14:42:20

回答

5

我刚刚找到这里面的R源之中的代码:

if (inError) { 
    /* fail-safe handler for recursive errors */ 
    if(inError == 3) { 
     /* Can REprintf generate an error? If so we should guard for it */ 
     REprintf(_("Error during wrapup: ")); 
     /* this does NOT try to print the call since that could 
      cause a cascade of error calls */ 
     Rvsnprintf(errbuf, sizeof(errbuf), format, ap); 
     REprintf("%s\n", errbuf); 
    } 

stop()导致要执行的错误处理程序。如果stop()调用发生在错误处理程序中,则R将显示Error during wrapup:消息,并阻止您进行无限递归,否则将会发生这种情况。

请勿在options$error之内拨打stop()

改为使用q(save="no", status=1, runLast=FALSE),它应该完成默认错误处理程序为非交互式使用所做的操作。有关错误处理的详细信息,请参阅?options以了解options$error?stop的含义。

相关问题