【问题标题】:Is there a way to save RStudio console warnings and messages? Sink() doesn't work有没有办法保存 RStudio 控制台警告和消息?水槽()不起作用
【发布时间】:2021-07-01 10:50:18
【问题描述】:

我运行了一个产生以下消息的函数:

[Output truncated]No imagary was found at location 13.51418,100.525398094512No imagary was found at location 13.5142126237624,100.519283133217No imagary was found at location 13.5142452475248,100.667925324763No imagary was found at location 13.5142778712871,100.633407407186No imagary was found at location 13.5143104950495,100.615685968347No imagary was found at location 13.5143431188119,100.438773863735No imagary was found at location 13.5143757425743,100.584423279119No imagary was found at location 13.5144083663366,100.518027443291No imagary was found at location 13.514440990099,100.675459782113No imagary was found at location 13.5144736138614,100.667897127582No imagary was found at location 13.5145062376238,100.632888261162No imagary was found at location 13.5145388613861,100.627567350767No imagary was found at location 13.5145714851485,100.495578874954trying URL 'https://maps.googleapis.com/maps/api/streetview?&location=13.5146041089109,100.687791167767&size=8000x5333&heading=0&fov=90&pitch=0&

但是,当我运行sink() 和我的函数(此处省略详细信息)时,my_output.txt 文件没有保存上面的控制台输出。有谁知道如何解决这个问题以便保存警告和消息?

代码:

sink(file = 'my_output.txt') 

MyFunction(...)

sink()

注意:我查看过类似的查询,例如 How to capture warnings with the console output?,但怀疑有更简单的解决方案?

【问题讨论】:

标签: r sink


【解决方案1】:

您必须为output 打开一个sink,为message 打开一个,但它们可以拥有相同的文件。

FN <- tempfile()
zz <- file(FN, open = "wt")
sink(zz ,type = "output")
sink(zz, type = "message")

print("using print")
cat("using cat\n")
message("using message")
warning("using warning")

sink(type = "output")
sink(type = "message")

cat(readLines(FN), sep="\n")
#[1] "using print"
#using cat
#using message
#Warning message:
#using warning 

unlink(FN)

【讨论】:

    【解决方案2】:

    您可以在创建错误的脚本之后运行函数warnings()。此函数返回最后显示的错误。因此,您可以创建一个带有错误消息的对象,然后将其写入 .txt(如果需要):

    YourFunctionNotWorking
    error <- names(warnings())
    out<-file("abc.txt")
    writeLines(error, out)
    close(out)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多