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.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With