Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Combining cmd.StdoutPipe and Cmd.StderrPipe

Tags:

go

exec

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!

like image 579
zsolt.k Avatar asked Mar 14 '16 18:03

zsolt.k


Video Answer


1 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
like image 169
Bayta Darell Avatar answered Nov 12 '22 01:11

Bayta Darell