Go stdout stream from async command

Viewed 4237

I want to use GO to run an asynchronous command on windows 10. The command I am running is blocking, and if run directly from the terminal it provides a constant steam of status messages until ctrl-c

I want to run that command from GO via exec and catch the output from the exec command to the terminal in real time, i.e. not only when the GO application terminates.

I have tried numerous examples but with not success, I just get a blank terminal and even after exiting the GO application, I don't see the output from the command I executed.

2 Answers

You can use cmd.StdoutPipe to do that:

cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, _ := cmd.StdoutPipe()
scanner := bufio.NewScanner(cmdReader)
done := make(chan bool)
go func() {
    for scanner.Scan() {
        fmt.Printf(scanner.Text())
    }
    done <- true
}()
cmd.Start()
<- done
err = cmd.Wait()

You can use io.MultiWriter to capture output and forward it to stdout and stderr.

var stdoutBuf, stderrBuf bytes.Buffer

cmd := exec.Command("/some-command")
cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
cmd.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
err := cmd.Start()  // Starts command asynchronously

if err != nil {
    fmt.Printf(err.Error())
}
Related