Yihui Yihui - 1 month ago 11
R Question

How to capture the output of system()

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


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()
.




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

CL. CL.
Answer

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.

Comments