如何捕获system()的输出 [英] How to capture the output of system()

查看:116
本文介绍了如何捕获system()的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是由 Rmarkdown不会将系统命令的结果输出到html文件引起的.出于某种原因,R(或system2())中system()的输出无法被sink()capture.output()捕获,因此当前没有 knitr 记录输出的方法.例如,在R控制台中:

This question was motivated by Rmarkdown not outputting results of system command to html file. For some reason, the output of system() in R (or system2()) cannot be captured by sink() or capture.output(), so currently there is no way for knitr to record the output. For example, in the R console:

> system('ls')
DESCRIPTION
NAMESPACE
R
README.md
inst
man

但是在 knitr 文档中,您将看不到输出,因为capture.output(system('ls'))character(0),即无法捕获输出.正如我在该问题的答案中提到的,我当然可以做cat(system('ls', intern = TRUE), sep = '\n'),但这有点尴尬.我想知道这是否是一种无需使用intern = TRUEcat()即可捕获system()输出的方法.

but in a knitr document, you won't see the output, because capture.output(system('ls')) is character(0), i.e. the output cannot be captured. Of course I can do cat(system('ls', intern = TRUE), sep = '\n') as I mentioned in the answer of that question, but this is kind of awkward. I wonder if it is a way to capture the output of system() without using intern = TRUE and cat().

更新:请参见 https://github.com/yihui /knitr/issues/1203 为我提供的用于解决该问题的黑客.

Update: see https://github.com/yihui/knitr/issues/1203 for a hack that I provided to solve the problem.

推荐答案

您可以添加掩盖base::system的函数knitr::system.用户可以像system::base一样使用它,但是输出可以由capture.output捕获:

You could add a function knitr::system that masks base::system. Users could work with it like it was system::base, but the output can be captured by capture.output:

system <- function(...) {
  stopifnot(!any(names(list(...)) %in% "intern"))
  result <- base::system(..., intern = TRUE)
  print(result)
}

我承认,这有点怪异,老实说,我不确定可能的副作用.但我认为值得一试.

I admit, that this is somewhat hacky, and to be honest, I'm not sure about possible side effects. But I think it could be worth a try.

这篇关于如何捕获system()的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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