【问题标题】:How to capture warnings with the console output?如何使用控制台输出捕获警告?
【发布时间】:2014-09-20 12:30:46
【问题描述】:

我正在尝试捕获我的 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()捕获。

【问题讨论】:

  • R CMD BATCH script.R 产生一个文件 script.Rout 和完整的会话;也许这与您的用例一致? (R CMD BATCH --vanilla --silent 以避免意外加载保存的工作空间并避免启动画面)。

标签: r


【解决方案1】:

几乎明白了,但它很复杂,而且很烦人,与标准输出不同,消息输出不能拆分,即重定向到文件并同时保留在输出中(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):无法拆分 消息连接

这很烦人!

【讨论】:

    【解决方案2】:

    我编写了以下函数来捕获输出和消息:

    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")
    }
    

    【讨论】:

    • 这与我在回答中得到的相同,但它仍然有缺点,即没有将警告和错误拆分到标准输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多