Ohenepee Peps
Ohenepee Peps

Reputation: 167

How to get full Stdout from exec.Command?

I have this code which I would also want to get the full output from cmd.Stdout when its done for text extraction, etc.

func main() {
    cmd := exec.Command("readinggame")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

I can't seem to find a way of getting the output either as []byte or string when its done. BTW I don't want to be iterating over the output with ReadLine (or something similar) which happens to work well, I just want a full output at a go, something like

var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
    log.Fatal(err)
}
fmt.Println(out.String())

Upvotes: 3

Views: 1562

Answers (1)

Ohenepee Peps
Ohenepee Peps

Reputation: 167

This is EXACTLY the expected result... all that was needed was io.MultiWriter.

func main() {

    cmd := exec.Command("ping", "google.com")

    var out bytes.Buffer
    multi := io.MultiWriter(os.Stdout, &out)
    cmd.Stdout = multi

    if err := cmd.Run(); err != nil {
        log.Fatalln(err)
    }

    fmt.Printf("\n*** FULL OUTPUT *** %s\n", out.String())

}

Upvotes: 4

Related Questions