I would like to execute a command in Go, and combining its stdout and stderr into one stream. I wrote this code, its read only from the stdout, but I don't know how to I combine it with the stderr:
package main
import (
"fmt"
"os"
"os/exec"
"bufio"
)
func runCommand() {
var (
err error
)
cmdName := "docker"
cmdArgs := []string{"build", "--no-cache=true", "--force-rm=true", "."}
cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("docker build out | %s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
}
}
func main() {
runCommand()
}
Thanks for all answers!
To combine stdout and stderr to a single reader, assign a single pipe to Command.Stdout and Command.Stderr:
cmdReader, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With