Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture both exit status and output from a system call in R

Tags:

I've been playing a bit with system() and system2() for fun, and it struck me that I can save either the output or the exit status in an object. A toy example:

X <- system("ping google.com",intern=TRUE) 

gives me the output, whereas

X <- system2("ping", "google.com") 

gives me the exit status (1 in this case, google doesn't take ping). If I want both the output and the exit status, I have to do 2 system calls, which seems a bit overkill. How can I get both with using only one system call?

EDIT : I'd like to have both in the console, if possible without going over a temporary file by using stdout="somefile.ext" in the system2 call and subsequently reading it in.

like image 755
Joris Meys Avatar asked Aug 10 '11 16:08

Joris Meys


2 Answers

As of R 2.15, system2 will give the return value as an attribute when stdout and/or stderr are TRUE. This makes it easy to get the text output and return value.

In this example, ret ends up being a string with an attribute "status":

> ret <- system2("ls","xx", stdout=TRUE, stderr=TRUE) Warning message: running command ''ls' xx 2>&1' had status 1  > ret [1] "ls: xx: No such file or directory" attr(,"status") [1] 1 > attr(ret, "status") [1] 1 
like image 64
wch Avatar answered Oct 20 '22 10:10

wch


I am a bit confused by your description of system2, because it has stdout and stderr arguments. So it is able to return both exit status, stdout and stderr.

> out <- tryCatch(ex <- system2("ls","xx", stdout=TRUE, stderr=TRUE), warning=function(w){w}) > out <simpleWarning: running command ''ls' xx 2>&1' had status 2> > ex [1] "ls: cannot access xx: No such file or directory" > out <- tryCatch(ex <- system2("ls","-l", stdout=TRUE, stderr=TRUE), warning=function(w){w}) > out  [listing snipped]                   > ex  [listing snipped] 
like image 35
Ido Tamir Avatar answered Oct 20 '22 09:10

Ido Tamir