从R中的系统调用中捕获退出状态和输出 [英] Capture both exit status and output from a system call in R

查看:77
本文介绍了从R中的系统调用中捕获退出状态和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在和system()system2()一起玩耍,这让我很惊讶,我可以将输出或退出状态保存在一个对象中.一个玩具示例:

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)

为我提供输出,而

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

给我退出状态(在这种情况下,为1,google不执行ping操作).如果我既要输出又要退出状态,则必须执行2次系统调用,这似乎有点过头了.如何仅使用一个系统调用就可以同时获得两者?

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?

我希望在控制台中同时具有这两个功能,如果可能的话,不通过在system2调用中使用stdout="somefile.ext"并随后将其读入来遍历临时文件.

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.

推荐答案

从R 2.15开始,当stdout和/或stderr为TRUE时,system2将给出返回值作为属性.这样可以轻松获取文本输出和返回值.

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.

在此示例中,ret最终是具有属性"status"的字符串:

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

这篇关于从R中的系统调用中捕获退出状态和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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