as.*_*ieu 2 command-line parsing go
我正在练习使用 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
我的问题是:如果我想解析平均响应时间,那么我可以将它分配给一个变量,以便我可以在需要时显示它,我该如何解析它?