流执行命令StdoutPipe

流执行命令StdoutPipe

问题描述:

I'm trying to stream the Stdout of a shell command to the console, but am having difficulty.

Here's what I currently have:

cmd := exec.Command("sh", "-c", `for number in {0..10}; do echo "$number "; done;`)
pipe, _ := cmd.StdoutPipe()
reader := bufio.NewReader(pipe)
line, err := reader.ReadString('
')
for err == nil {
    fmt.Println(line)
    line, err = reader.ReadString('
')
}

I would expect this to print out the numbers 0 through 10, but it seems to hang on line 3 (the first call to ReadString.

I started with cmd.Output() and cmd.CombinedOutput(), but those methods seem to buffer the entire output stream until the command is complete. I need to process the output as it streams, not wait until the command is complete.

I also tried this: continuously reading from exec.Cmd output, but it didn't seem to work and I went away from it because I really want to read lines and not have to manage the buffer manually.

Other things I've looked through:

我正在尝试将Shell命令的标准输出流式传输到控制台,但是遇到了困难。 p >

这是我目前拥有的: p>

  cmd:= exec.Command(“ sh”,“ -c”,`用于{0中的数字 ..10};回显“ $ number”;完成;​​`)
pipe,_:= cmd.StdoutPipe()
reader:= bufio.NewReader(pipe)
line,err:= reader.ReadString('
  ')
for err == nil {
 fmt.Println(line)
 line,err = reader.ReadString('
')
} 
  code>  pre> 
 
 我希望它能打印出0到10的数字,但它似乎挂在第3行(第一次调用 ReadString  code>。 p> 
 
 

我开始了 使用 cmd.Output() code>和 cmd.CombinedOutput() code>,但是这些方法似乎会缓冲整个输出流,直到命令完成为止。我需要将输出处理为 它会流式传输,而不要等到命令完成。 p>

我还尝试了以下方法:连续读取exec.Cmd输出,但是它似乎不起作用,我放弃了它,因为我真的想读取行,而不必手动管理缓冲区。 / p>

我浏览过的其他内容: p>

You need to start the command:

cmd := exec.Command("sh", "-c", `for number in {0..10}; do echo "$number "; done;`)
pipe, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
   // handle error
}
reader := bufio.NewReader(pipe)
line, err := reader.ReadString('
')
for err == nil {
    fmt.Println(line)
    line, err = reader.ReadString('
')
}

Call Wait after reaching EOF.

The Output and CombinedOutput methods worked for you because these methods call Start internally.