简体   繁体   English

在R中的函数中捕获系统命令的输出

[英]Capture output of system command within a function in R

I'm working with a function in a package that uses system2() to run a command within the function. 我正在使用使用system2()在函数内运行命令的包中的函数。 This particular command prints some stuff to standard out. 这个特定的命令可以打印出一些标准的东西。 I want to capture the output of that system2() call, however capture.output() does not work. 我想捕获该system2()调用的输出,但是capture.output()不起作用。 I understand how to run system2() directly and capture the standard output, but not how to get it in this specific situation. 我了解如何直接运行system2()并捕获标准输出,但不了解如何在这种特定情况下获取它。

Simple example: 简单的例子:

my_ls <- function() {
  system2("ls")
  return("Hello")
}
my_ls()
output <- capture.output(my_ls())
output

Here's a solution... But be warned, it works for me on Linux, might work on a Mac, and I doubt it works on Windows... 这是一个解决方案...但是请注意,它在Linux上适用于我,在Mac上可能适用,并且我怀疑它在Windows上适用...

Create two Rcpp functions: 创建两个Rcpp函数:

library(Rcpp)
cppFunction('void redir(){FILE* F=freopen("/tmp/capture.txt","w+",stdout);}')
cppFunction('void resetredir(){FILE* F=freopen("/dev/tty","w+",stdout);}')

The first will send everything to that file. 第一个将所有内容发送到该文件。 The second will reset it. 第二个将重置它。 The problem is that interactively after the first you'll not be able to see anything. 问题是在第一次互动之后,您将看不到任何东西。 So beware... 所以要当心...

So initially system2 sends to the console: 因此,最初, system2发送到控制台:

> system2("echo", "hello")
hello

But wrapping a call in redir / resetredir sends it to the file: 但是将调用包装在redir / resetredir会将其发送到文件:

> redir(); system2("echo","hello world this time") ; resetredir()
> # prompt returns!

Now we have: 现在我们有:

$ cat /tmp/capture.txt 
hello world this time

and if this is the output from some other package you'll have to read it in with R's file I/O routines. 如果这是其他软件包的输出,则必须使用R的文件I / O例程读取它。

The dodgy bit is the use of /dev/tty in the reset code - I'm not sure it works on a Mac or Windows. 狡猾的地方是在重置代码中使用了/dev/tty我不确定它是否可以在Mac或Windows上使用。 If you don't care about resetting the stdout then skip it, and just make sure you know how to quite R without seeing what you type. 如果您不关心重置标准输出,请跳过它,并确保您知道如何使用R而不看到输入内容。 I'm also unsure if this will work in RStudio which probably has a different concept of the console.... 我也不确定这是否可以在RStudio中使用,后者可能具有不同的控制台概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM