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 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)