Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go stdout stream from async command

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.

like image 965
PrestonDocks Avatar asked Oct 28 '25 03:10

PrestonDocks


1 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()
like image 119
dave Avatar answered Oct 30 '25 14:10

dave