我们可以使用system2 调用来获取shell 中ping 命令的返回状态。在 Windows(可能还有 linux)上,以下将起作用:
ping <- function(x, stderr = FALSE, stdout = FALSE, ...){
pingvec <- system2("ping", x,
stderr = FALSE,
stdout = FALSE,...)
if (pingvec == 0) TRUE else FALSE
}
# example
> ping("google.com")
[1] FALSE
> ping("ugent.be")
[1] TRUE
如果要捕获ping的输出,可以设置stdout = "",或者使用系统调用:
> X <- system("ping ugent.be", intern = TRUE)
> X
[1] "" "Pinging ugent.be [157.193.43.50] with 32 bytes of data:"
[3] "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62" "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"
[5] "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62" "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"
[7] "" "Ping statistics for 157.193.43.50:"
[9] " Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)," "Approximate round trip times in milli-seconds:"
[11] " Minimum = 0ms, Maximum = 0ms, Average = 0ms"
使用选项intern = TRUE 可以将输出保存在向量中。我把它留给读者作为练习,重新排列它以获得一些不错的输出。