2014-09-20 116 views
2

我想捕获我的R脚本的完整控制台日志。我想要按时间顺序排列所有事物,并在发生时印刷警告。我试过这个:如何使用控制台输出捕获警告?

options(warn = 1) 

tmpSinkfileName <- tempfile() 
sink(tmpSinkfileName, split = TRUE) 

cat("Doing something\n") 
warning("Hi here") 
cat("Doing something else\n") 
warning("Hi there") 

sink() 
console.out <- readChar(tmpSinkfileName, file.info(tmpSinkfileName)$size) 
unlink(tmpSinkfileName) 

cat(console.out) 
# Doing something 
# Doing something else 
warnings() 
# NULL 

但不幸的是在console.out中缺少警告。我怎样才能做到这一点?根据文档,options(warn = 1)应该在发生警告时进行打印。不幸的是,他们没有被sink()捕获。

+0

的r CMD BATCH script.R'产生具有完整的会话的文件script.Rout;也许这与你的用例一致? ('R CMD BATCH --vanilla --silent'以避免意外加载保存的工作空间并避免启动画面)。 – 2014-09-20 12:55:13

回答

3

几乎得到它,但它非常复杂,与标准输出不同,消息输出不能被拆分,即重定向到文件并同时保存在输出中(UNIX tee行为)!

options(warn = 1) 

tmpSinkfileName <- tempfile() 
tmpFD <- file(tmpSinkfileName, open = "wt") 
sink(tmpFD, split = TRUE) 
sink(tmpFD, type = "message") 

cat("Doing something\n") 
warning("Hi here") 
cat("Doing something else\n") 
warning("Hi there") 

sink(type = "message") 
sink() 
console.out <- readChar(tmpSinkfileName, file.info(tmpSinkfileName)$size) 
unlink(tmpSinkfileName) 

cat(console.out) 

如果我尝试

sink(tmpFD, type = "message", split = TRUE) 

错误在水槽(tmpFD,类型= “消息”,分裂= TRUE)表示:不能分割 的消息连接

这非常讨厌!

3

我写下面的函数来捕获输出中和消息:

create_log <- function(logfile_name, path) { 
    if (file.exists(paste0(path, logfile_name))) { 
    file.remove(paste0(path, logfile_name)) 
    } 
    fid <- file(paste0(path, logfile_name), open = "wt") 
    sink(fid, type = "message", split = F) 
    sink(fid, append = T, type = "output", split = T) 
    warning("Use closeAllConnections() in the end of the script") 
}