1

I know how to capture the output of a exec.Command but I would like to also stream it to stdout while still capturing it. Thanks for any input!

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    cmd.Stdout = &out
    cmd.Run()
    fmt.Println(out.String())
}
3
  • 6
    Either using io.TeeReader() or io.MultiWriter(). For an example, see What is the difference between io.TeeRearder and io.Copy? Commented Apr 13, 2022 at 14:23
  • 2
    ls may be a toy example here. But if not, it's preferred to use native Go APIs (like os.ReadDir) rather than launching an external executable. Commented Apr 13, 2022 at 14:48
  • @colm.anseo Yes, that was only to shorten the example :) Commented Apr 14, 2022 at 9:57

1 Answer 1

3

Example using io.MultiWriter

package main

import (
    "io"
    "os"
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    var out bytes.Buffer
    w := io.MultiWriter(os.Stdout, &out)
    cmd.Stdout = w
    fmt.Printf("===Stdout:===\n")
    cmd.Run()
    fmt.Printf("\n===Variable:===\n")
    fmt.Println(out.String())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.