douya7121 2017-10-13 05:50
浏览 373
已采纳

流执行命令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:

  • 写回答

1条回答 默认 最新

  • douke9545 2017-10-13 06:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏