如何在 R 中抑制 download.file() "trying URL..." 消息?

How to suppress download.file() "trying URL..." message in R?

我知道该函数有一个 quiet 参数,但我试图在 quiet = FALSE.

时抑制该消息

这可能很奇怪,但我在测试我正在编写的包时遇到了这个问题。我在设置 quiet = FALSE 时使用 testthat::expect_message(),但该函数实际上并没有抑制消息(它应该,而且实际上它通常对“正常”消息进行抑制)。

我用 suppressMessages() 试过了,但没有按预期工作:

url <- "https://github.com/ipeaGIT/gtfstools/raw/master/inst/extdata/spo_gtfs.zip"
download.file(url, destfile = tempfile(), quiet = FALSE)
#> trying URL 'https://github.com/ipeaGIT/gtfstools/raw/master/inst/extdata/spo_gtfs.zip'
#> Content type 'application/zip' length 191108 bytes (186 KB)
#> downloaded 186 KB

suppressMessages(download.file(url, destfile = tempfile(), quiet = FALSE))
#> trying URL 'https://github.com/ipeaGIT/gtfstools/raw/master/inst/extdata/spo_gtfs.zip'
#> Content type 'application/zip' length 191108 bytes (186 KB)
#> downloaded 186 KB

关于如何抑制它的任何想法,最好不改变任何 options?这不是危及生命的情况,但让我很好奇。

suppressMessages() 不起作用,因为进度文本不是 R message(),它是 download.file() 将实际下载委托给的系统库​​的标准输出(例如libcurlwgetwininet)。 quiet = TRUE 通过设置该工具的适当命令行选项绕过此问题。

您可以使用 sink() 将标准输出从 R 控制台转移到文件中。由于你不需要它,你可以使用nullfile()打开一个到依赖于平台的空设备的文件连接:

url <- "https://github.com/ipeaGIT/gtfstools/raw/master/inst/extdata/spo_gtfs.zip"

nullcon <- file(nullfile(), open = "wb")
sink(nullcon, type = "message")
download.file(url, destfile = tempfile(), quiet = FALSE)
sink(type = "message")
close(nullcon)

请注意,倒数第二行非常重要——它结束了转移。没有它,R 会话中的所有其他消息都将发送到 /dev/null.

还请记住来自 ?sink 的以下警告:

Do not use a connection that is open for sink for any other purpose. The software will stop you closing one such inadvertently.

Do not sink the messages stream unless you understand the source code implementing it and hence the pitfalls.

我个人认为这种方法在包中使用风险太大,尤其是当 quiet = TRUE 选项可用时。