我正在嘗試從命令的標準輸出中解析一些錯誤。作為命令,我使用以下示例腳本:#!/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 關注
- 100 瀏覽
添加回答
舉報
0/150
提交
取消