R sink():错误,无法拆分消息连接 [英] R sink(): Error, cannot split the message connection

查看:51
本文介绍了R sink():错误,无法拆分消息连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将R脚本的错误和警告记录到外部文件中.同时,我希望能够在RStudio的控制台中看到错误和警告(用于开发和调试).我正在尝试使用以下代码:

I am trying to log the errors and warnings of an R script into an external file. At the same time I want to be able to see the errors and warnings in the console in RStudio (useful to develop and debug). I am trying to use the following code:

logfile <- file("my_file_path", open="wt")
sink(logfile, type="message", split = TRUE)

但是当我尝试使用功能接收器()拆分消息连接时,出现以下错误:

But when I try to split the message connection using the funciton sink() I get the following error:

Error in sink(logfile, type = "message", split = TRUE) : 
  cannot split the message connection

是否有任何解决方法或替代解决方案?

Is there any workaround or alternative solution?

谢谢

推荐答案

因此,我尝试在 sink 中使用 split = T .

So, I tried using split = T in sink.

但是,它没有按照我们想要的去做.要么将输出重定向到日志文件,要么抛出您指出的错误,而不是向RStudio控制台打印错误或警告消息.

But, it's not doing what we want it to do. It's either redirecting output to log file or throwing an error which you pointed and is not printing errors or warning messages to RStudio console.

有一些解决您的问题的方法,它可能会解决您的问题.

There's a work around to your problem which might solve your problem.

我尝试使用此功能:-

# path to your log file
file_path <- "path/documents/log/log.txt"

# open a connection to your log file
file_con <- file(file_path, open = "a")

## capture warning messages and errors to log file
sink(file_con, type = "message")

## to get error and warning message 
sum(a)
warning("this is a warning message. please ignore")

## revert output back to the console and close the file connection
sink(type = "message")
close(file_con)

# get all the errors and warnings from log file
readLines(file_path)

它向控制台提供了输出:-

It gave an output to console:-

[1] "Error: object 'a' not found"              
[2] "Warning message:"                         
[3] "this is a warning message. please ignore "

因此,以上代码将错误和警告消息转移到了日志文件中,并将其打印在控制台中.

So, the above piece of code diverted the error and warning message to log file and printed it in console too.

您可以正常使用 sink ,然后使用 readLines 将错误和警告消息打印到控制台.

You can use sink normally and then use readLines to print your error and warning messages to console.

这篇关于R sink():错误,无法拆分消息连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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