为了账号安全,请及时绑定邮箱和手机立即绑定

Golang Exec 命令长输出

Golang Exec 命令长输出

Go
白衣非少年 2022-04-20 21:07:40
如何从很长的 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=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply 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 回答

?
米脂

TA贡献1836条经验 获得超3个赞

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


func main() {

    args := "-n 30000 127.0.0.1"

    cmd := exec.Command("ping", strings.Split(args, " ")...)


    output, _ := cmd.StdoutPipe()

    cmd.Start()


    scanner := bufio.NewScanner(output)

    for scanner.Scan() {

        m := scanner.Text()


        matchPackets, _ := regexp.MatchString("Packets", m)

        matchMinimum, _ := regexp.MatchString("Minimum", m)


        if matchPackets {

            fmt.Println("Ping statistics for 127.0.0.1")

            fmt.Println(m)

        }


        if matchMinimum {

            fmt.Println("Approximate round trip times in milli-seconds:")

            fmt.Println(m)

        }

    }

    cmd.Wait()

}


查看完整回答
反对 回复 2022-04-20
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号