我正在尝试从命令的标准输出中解析一些错误。作为命令,我使用以下示例脚本:#!/bin/bashfor i in {1..4}do echo "[the script] working... working..." sleep 0.5s echo "[error 1010] This is an error that occured just in this moment." sleep 0.5sdoneexit 41我的解析代码如下所示(导入缩短):func main() { cmd := exec.Command("./test.sh") os.Exit(stdOutPipe(cmd))}func stdOutPipe(cmd *exec.Cmd) int { stdout, _ := cmd.StdoutPipe() cmd.Start() chunk := make([]byte, 20) for { _, err := stdout.Read(chunk) if err != nil { break } s := string(chunk) if strings.Contains(s, "error 1010") { fmt.Println("[your genius go tool] There occurred an ERROR and it's number ist 1010!") break } fmt.Print(s) } cmd.Wait() return cmd.ProcessState.ExitCode()}我得到以下输出:$ go run main.go[the script] working... working...rking[your genius go tool] There occurred an ERROR and it's number ist 1010!exit status 41输出的第二行从前段行重复“rking”。我该如何摆脱这种情况?如果你能解释为什么会发生这种重复,那也会很好。
1 回答

慕妹3242003
TA贡献1824条经验 获得超6个赞
您正在丢弃 的返回值。这给出了读取了多少字节。read
n, err := stdout.Read(chunk)
s:=string(chunk[:n])
if strings.Contains(s, "error 1010") {
fmt.Println("[your genius go tool] There occurred an ERROR and it's number ist 1010!")
break
}
fmt.Print(s)
if err != nil {
break
}
根据阅读文档:
如果某些数据可用但不能使用 len(p) 字节,则 Read 通常会返回可用数据,而不是等待更多数据
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消