Golang Exec 命令长输出

如何从很长的 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,这不是我在看的。我说的对吗?


白衣非少年
浏览 122回答 1
1回答

米脂

我认为以下代码是我需要的:func main() {&nbsp; &nbsp; args := "-n 30000 127.0.0.1"&nbsp; &nbsp; cmd := exec.Command("ping", strings.Split(args, " ")...)&nbsp; &nbsp; output, _ := cmd.StdoutPipe()&nbsp; &nbsp; cmd.Start()&nbsp; &nbsp; scanner := bufio.NewScanner(output)&nbsp; &nbsp; for scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; m := scanner.Text()&nbsp; &nbsp; &nbsp; &nbsp; matchPackets, _ := regexp.MatchString("Packets", m)&nbsp; &nbsp; &nbsp; &nbsp; matchMinimum, _ := regexp.MatchString("Minimum", m)&nbsp; &nbsp; &nbsp; &nbsp; if matchPackets {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Ping statistics for 127.0.0.1")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(m)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if matchMinimum {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Approximate round trip times in milli-seconds:")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(m)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; cmd.Wait()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go