doukuangxiu1621 2015-06-18 19:29
浏览 65
已采纳

Golang管道实时输出子命令

I am trying to pipe the output of a command, but no data seems to be read from the pipe until the write end is closed. Eventually I want this to connect to a websocket that streams the status of a command while it is being executed. The problem is that while this code prints the messages line by line, it does not print anything until the program has finished executing.

cmd := exec.Command(MY_SCRIPT_LOCATION, args)

// create a pipe for the output of the script
// TODO pipe stderr too
cmdReader, err := cmd.StdoutPipe()
if err != nil {
    fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
    return
}

scanner := bufio.NewScanner(cmdReader)
go func() {
    for scanner.Scan() {
        fmt.Printf("\t > %s
", scanner.Text())
    }
}()

err = cmd.Start()
if err != nil {
    fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
    return
}

err = cmd.Wait()
if err != nil {
    fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
    return
}

Is there any way I can do something similar and have a scanner actually read line by line as it is written to the pipe instead of after everything has been written? The program takes about 20 seconds to run, and there is a steady stream of updates, so it is annoying to have them all go through at once.

  • 写回答

1条回答 默认 最新

  • duanbinmi8970 2015-06-18 22:36
    关注

    Turns out that the issue was not in the code I posted above. That works as expected. The problem was that the C program that was being executed was not properly flushing stdout. When running it interactively, it worked as expected, but when stdout was piped, it would not actually get written until I called flush. After manually adding some flush statements to the c program, the go code worked as expected.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题