为什么从 Stdout.Pipe 读取会重复文本?

我正在尝试从命令的标准输出中解析一些错误。作为命令,我使用以下示例脚本:


#!/bin/bash

for 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.5s

done

exit 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”。我该如何摆脱这种情况?如果你能解释为什么会发生这种重复,那也会很好。


陪伴而非守候
浏览 114回答 1
1回答

慕妹3242003

您正在丢弃 的返回值。这给出了读取了多少字节。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 通常会返回可用数据,而不是等待更多数据
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go