首页 > 解决方案 > R 3.5 中的 system2() 忽略标准输出参数

问题描述

我最近从 R 3.4.3 升级到 R 3.5.1

我的应用程序进行了一个 system2() 调用,该调用在 windows 和 linux 上都适用于 3.4.3,但不再适用于 3.5.1 windows(但仍适用于 linux)。特别是,我的 system2() 调用将标准输出重定向到一个文件,但是在 R 3.5.1 的 Windows 上,它不会重定向,而是将输出发送到控制台。

有没有人有这个问题的经验?我没有找到任何关于改变 system2 应该如何工作的注释;我是否错过了对其行为的预期变化?我可以使用任何解决方法来让它工作吗?

我创建了这个代码片段来演示这个问题:

version$version.string
unlink("output.txt")
file.exists("output.txt")
system2("cmd", args = c("/c", "echo", "hello world"), stdout = TRUE)
system2("cmd", args = c("/c", "echo", "hello world"), stdout = "output.txt")
file.exists("output.txt")
readLines("output.txt")

3.4.3 的输出:

> version$version.string
[1] "R version 3.4.3 (2017-11-30)"
> unlink("output.txt")
> file.exists("output.txt")
[1] FALSE
> system2("cmd", args = c("/c", "echo", "hello world"), stdout = TRUE)
[1] "hello world"
> system2("cmd", args = c("/c", "echo", "hello world"), stdout = "output.txt")
> file.exists("output.txt")
[1] TRUE
> readLines("output.txt")
[1] "hello world"

windows上3.5.1的输出:

> version$version.string
[1] "R version 3.5.1 (2018-07-02)"
> unlink("output.txt")
> file.exists("output.txt")
[1] FALSE
> system2("cmd", args = c("/c", "echo", "hello world"), stdout = TRUE)
[1] "hello world"
> system2("cmd", args = c("/c", "echo", "hello world"), stdout = "output.txt")
hello world
> file.exists("output.txt")
[1] FALSE
> readLines("output.txt")
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file 'output.txt': No such file or directory

linux 上 3.5.1 的输出:

> version$version.string
[1] "R version 3.5.1 (2018-07-02)"
> unlink("output.txt")
> file.exists("output.txt")
[1] FALSE
> system2("echo", args = c("hello world"), stdout = TRUE)
[1] "hello world"
> system2("echo", args = c("hello world"), stdout = "output.txt")
> file.exists("output.txt")
[1] TRUE
> readLines("output.txt")
[1] "hello world"

标签: rrstudio

解决方案


我能够使用修补了 R 3.5.1 的 RGui 重现这一点——我将此作为 R 核心团队的错误报告提交。https://bugs.r-project.org/bugzilla3/show_bug.cgi?id=17508

编辑:虽然我不确定这是否是故意的,但我相信这是负责更改的提交:

https://github.com/wch/r-source/commit/a0217674cba49d50a24dd42ea156f78687bd8de3

为了适应行为的变化,您可以设置stderr参数——例如,这应该有效:

args <- c("/c", "echo", "hello")
system2("cmd", args = args, stdout = "output.txt", stderr = FALSE)

推荐阅读