我正在使用网格引擎来运行R脚本。 STDERR在这个设置下被认真对待,所以我想保持它干净,只有真正/严重/致命错误打印到STDERR。
问题是我的R脚本生成了各种STDERR消息,这些消息并不是真正严重的警告...例如,scan
似乎向STDERR打印了它读取的项目数。
我可以将(从R中)STDERR重定向到STDOUT吗?
答案 0 :(得分:6)
查看sink()
的帮助页面:
'sink'将R输出转移到连接。如果'file'是一个字符 string,将为其建立具有该名称的文件连接 转移的持续时间。
正常R输出(连接'stdout')被转移 默认'type =“输出”'。仅提示和(大多数)消息 继续出现在控制台上。发送给'stderr()'的消息 (包括来自'消息','警告'和'停止'的那些)可以 被'sink(type =“message”)'转移(见下文)。
答案 1 :(得分:2)
@Dirk已经提供了答案,但我想补充一点,你可以使用stdout()
来获得与STDOUT的连接。您可以在任何输出函数中使用它来指示输出。
答案 2 :(得分:0)
隔离错误的一种方法是使用 try catch,在主块中,所有内容都发送到 stdout,然后代码抛出的任何错误都被捕获并发送到 stderr。
这只会处理代码中抛出的错误,而不是记录错误消息,但可能是您的解决方案。
result = tryCatch({
sink(stdout(), type = "message") # sink all messages, warnings, errors to stdout
message('Starting! This message will go to stdout')
warning('Warning! This message will go to stdout')
error('Error! This message will ALSO go to stdout')
#Call your code here, e.g.
#...
stop('An error is thrown', call.=FALSE)
#...
}, error = function(e) {
sink(NULL, type="message") # close the sink
#Now sink closed, you can re-raise the error, and it will be directed to sterr:
stop(paste0('Error: ', e), call.=FALSE)
})