为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
陪伴而非守候 2022-08-15 19:47:08
我正在尝试从命令的标准输出中解析一些错误。作为命令,我使用以下示例脚本:#!/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 通常会返回可用数据,而不是等待更多数据


查看完整回答
反对 回复 2022-08-15
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号