Golang Exec命令长输出

时间:2019-12-05 21:52:21

标签: go ping

如何从很长的ping命令输出中仅获取ping统计信息:

func main() {
    cmdout, _ := exec.Command("ping", "127.0.0.1", "-n", "30000").Output()
    fmt.Printf("%s\n", cmdout)
}

我只需要以下输出:

Ping statistics for 127.0.0.1:
    Packets: Sent = 30000, Received = 30000, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

输出如下:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
...............................................

我只想丢弃。我当时正在考虑将所有这些输出转换成一个变量,然后解析它,直到获得所需的结果:

output := string(out)
    scanner := bufio.NewScanner(strings.NewReader(output))
    for scanner.Scan() {
        fmt.Println("Line: ", scanner.Text())
        regex compile etc...
    }

但是,我不确定这是否是一种有效的模式,通过选择这种方式意味着用大量未使用的数据填充RAM,这不是我要关注的。我是对的吗?

1 个答案:

答案 0 :(得分:1)

我认为以下代码是我所需要的:

router!(request,
    (GET) (/{path: PathBuf}) => {
        handle_path(path.as_path())
    },
    _ => Response::empty_400()
)