【问题标题】:R sink() message and output to same file - sanity checkR sink() 消息并输出到同一个文件 - 完整性检查
【发布时间】:2020-03-25 23:52:51
【问题描述】:

我正在使用 R 的 sink() 函数将错误、警告、消息和控制台输出捕获到单个文本文件中。

我想知道同时将 messageoutput 类型放入一个打开的文件是否不好?

我将以上所有内容都捕获到一个文件中,但我必须打开一个文件句柄以允许捕获两种接收器类型。以下代码说明了使用文件句柄方法:

message_filename = 'script_messages.txt'
try(message_file <- file(message_filename, open="at")) # open file for appending in text mode
sink(message_file, type="message")
sink(message_file, type="output")

cat("\n\n")
message(format(Sys.time(), "%a %b %d %Y %X TZ(%z)"), appendLF = TRUE)
# next line produces messages since file doesn't exist
try(source("import_file.R"), silent = TRUE)

# Save and close writing errors, warnings, messages, and console output to a file
sink(type="output")
sink(type="message")
close(message_file)

如果我不打开文件句柄,那么接收器“输出”类型的消息是唯一在文本文件中捕获的消息。

关于 sink {base} 的文档在 Details 部分的前半部分有一些关键信息,但我不够流利,无法确定我已经正确实现了它。

【问题讨论】:

    标签: r file error-handling output sink


    【解决方案1】:

    我相信这与警告的全局选项有关。默认值为warn=0,即"warnings are stored until the top–level function returns"。换句话说,当你 source("script.R") 时,R 会存储警告并在你的脚本完成后打印它们,即在你运行 sink(type="output"); sink(type="message"); close(message_file) 之后。

    要更改此设置,您可以在获取脚本之前调用options(warn=1),这将在警告发生时打印警告,因此会被您的接收器捕获。每个会话只需运行一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      相关资源
      最近更新 更多