R sink()消息并输出到同一文件-完整性检查 [英] R sink() message and output to same file - sanity check

查看:130
本文介绍了R sink()消息并输出到同一文件-完整性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using R's sink() function to capture errors, warnings, messages and console output into a single text file.

我想知道是否同时下沉消息输出类型都不能打开到单个打开文件中吗?

I'm wondering if simultaneously sinking both message and output types to a single open file is bad to do?

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

I capture all of the above into a single file, but I must open a file handle to allow both sink types to be captured. The following code illustrates using the file handle approach:

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)

如果我没有打开文件句柄,则接收器输出类型的消息是文本中唯一捕获的消息文件。

If I don't open a file handle, then the sink 'output' type messages are the only ones captured in the text file.

接收器{base}上的文档在详细信息部分的上半部分提供了一些关键信息,但我不太熟练,无法确定我已经实施

The documentation on sink {base} has some key info in the first half of the Details section, but I'm not fluent enough to be sure I've implemented it properly.

推荐答案

我相信这与警告的全局选项有关。默认值为 warn = 0 ,这表示警告会被存储,直到顶级函数返回 为止。换句话说,当您 source( script.R)时,R会存储警告并在脚本完成后(即运行 sink(type = output);下沉(类型=消息);关闭(邮件文件)

I believe it's to do with the global option for warn. The default is warn=0 which means "warnings are stored until the top–level function returns". In other words, when you source("script.R"), R stores up the warnings and prints them once your script has finished, i.e. after you've run sink(type="output"); sink(type="message"); close(message_file).

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

To change this you can call options(warn=1) before you source your script, this will print warnings as they occur and will therefore be caught by your sink. This only needs to be run once per session.

这篇关于R sink()消息并输出到同一文件-完整性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆