尝试使用Golang在命令行上解析stdout

时间:2017-02-13 21:35:33

标签: parsing go command-line

我正在练习使用GoLang将参数传递给命令行,并能够从传出的结果中解析信息。例如,我有代码用于执行命令,并显示无论如何通过cmd输入命令时显示的内容。

package main

import (
    "bytes"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

func main() {
    cmd = exec.Command("ping", "8.8.8.8")
    cmdOutput = &bytes.Buffer{}
    cmd.Stdout = cmdOutput
    printCommand(cmd)
    err = cmd.Run()
    printError(err)
    printOutput(cmdOutput.Bytes())
}

func printCommand(cmd *exec.Cmd) {
    fmt.Printf("==> Executing: %s\n", strings.Join(cmd.Args, " "))
}

func printError(err error) {
    if err != nil {
        os.Stderr.WriteString(fmt.Sprintf("==> Error: %s\n", err.Error()))
    }
}

func printOutput(outs []byte) {
    if len(outs) > 0 {
        fmt.Printf("==> Output: %s\n", string(outs))
    }
}

考虑输出将是:

==> Executing: ping 8.8.8.8
==> Output:
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=13ms TTL=56
Reply from 8.8.8.8: bytes=32 time=13ms TTL=56
Reply from 8.8.8.8: bytes=32 time=14ms TTL=56
Reply from 8.8.8.8: bytes=32 time=11ms TTL=56

Ping statistics for 8.8.8.8:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% lo
Approximate round trip times in milli-seconds:
    Minimum = 11ms, Maximum = 14ms, Average = 12ms

我的问题是:如果我想解析平均响应时间,那么我可以将其分配给变量,这样我可以在需要时显示,我该如何解析?

1 个答案:

答案 0 :(得分:3)

您可以使用regexp。例如:

package main

import (
        "bytes"
        "fmt"
        "os"
        "os/exec"
        "regexp"
        "strings"
        "time"
)

type Ping struct {
        average time.Duration
}

func main() {
        cmd := exec.Command("ping", "8.8.8.8")
        // Linux version
        //cmd := exec.Command("ping", "-c 4", "8.8.8.8")
        cmdOutput := &bytes.Buffer{}
        cmd.Stdout = cmdOutput
        printCommand(cmd)
        err := cmd.Run()
        printError(err)
        output := cmdOutput.Bytes()
        printOutput(output)
        ping := Ping{}
        parseOutput(output, &ping)

        fmt.Println(ping)
}

func printCommand(cmd *exec.Cmd) {
        fmt.Printf("==> Executing: %s\n", strings.Join(cmd.Args, " "))
}

func printError(err error) {
        if err != nil {
                os.Stderr.WriteString(fmt.Sprintf("==> Error: %s\n", err.Error()))
        }
}

func printOutput(outs []byte) {
        if len(outs) > 0 {
                fmt.Printf("==> Output: %s\n", string(outs))
        }
}

func parseOutput(outs []byte, ping *Ping) {
        var average = regexp.MustCompile(`Average = (\d+ms)`)
        result := average.FindStringSubmatch(string(outs))

        if len(result) > 0 {
                ping.average, _ = time.ParseDuration(result[1])
        }
        // Linux version
        /*var average = regexp.MustCompile(`min\/avg\/max\/mdev = (0\.\d+)\/(0\.\d+)\/(0\.\d+)\/(0\.\d+) ms`)
        result := average.FindAllStringSubmatch(string(outs), -1)

        if len(result) > 0 {
                ping.average, _ = time.ParseDuration(result[0][2] + "ms")
        }*/
}