Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为什么从标准管道读取会重复文本?_Go_Stdout - Fatal编程技术网

Go 为什么从标准管道读取会重复文本?

Go 为什么从标准管道读取会重复文本?,go,stdout,Go,Stdout,我正试图解析命令stdout中的一些错误。作为命令,我使用以下示例脚本: #/bin/bash 对于{1..4}中的i 做 echo“[脚本]正在工作…正在工作…” 睡眠0.5秒 echo“[error 1010]这是此时发生的错误。” 睡眠0.5秒 完成 41号出口 我的解析代码如下所示(导入缩短): func main(){ cmd:=exec.Command(“./test.sh”) 操作系统出口(stdOutPipe(cmd)) } func stdOutPipe(cmd*exec.c

我正试图解析命令stdout中的一些错误。作为命令,我使用以下示例脚本:

#/bin/bash
对于{1..4}中的i
做
echo“[脚本]正在工作…正在工作…”
睡眠0.5秒
echo“[error 1010]这是此时发生的错误。”
睡眠0.5秒
完成
41号出口
我的解析代码如下所示(导入缩短):

func main(){
cmd:=exec.Command(“./test.sh”)
操作系统出口(stdOutPipe(cmd))
}
func stdOutPipe(cmd*exec.cmd)int{
stdout,:=cmd.StdoutPipe()
cmd.Start()
区块:=生成([]字节,20)
为了{
_,err:=stdout.Read(块)
如果错误!=零{
打破
}
s:=字符串(块)
if strings.Contains(s,“错误1010”){
Println(“[您的genius go工具]出现错误,编号为IST1010!”)
打破
}
格式印刷品
}
cmd.Wait()
返回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

输出的第二行从previoius行重复“rking”。我怎样才能摆脱这个?如果您能解释为什么会发生这种重复,那也太好了。

您正在丢弃
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
 }
根据Read docs:

如果某些数据可用,但不是len(p)字节,则Read通常会返回可用的数据,而不是等待更多数据


您正在丢弃
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
 }
根据Read docs:

如果某些数据可用,但不是len(p)字节,则Read通常会返回可用的数据,而不是等待更多数据


,err:=stdout.Read(chunk)
不要忘记
n
chunk
中写入的字节数
,err:=stdout.Read(chunk)
不要忘记
n
chunk
中写入的字节数。谢谢,这解决了问题。你能简单地解释一下为什么读取的字节数不同吗?我的意思是,这是因为在回音shell脚本中这两行之间的睡眠时间造成的吗?如果文本还没有完成,为什么它不简单地读取尽可能多的字节呢?我编辑了我的答案,包括谢谢,这解决了问题。你能简单地解释一下为什么读取的字节数不同吗?我的意思是,这是因为在回音shell脚本中这两行之间的睡眠时间造成的吗?如果文本尚未完成,为什么它不简单地读取尽可能多的字节呢?我编辑了我的答案,将其包括在内