I am running an external process via exec.Command()
and I want the stdout from the command to be printed as well as written to file, in real time (similar to using tee
from a command-line) .
I can achieve this with a scanner and a writer:
cmd := exec.Command("mycmd")
cmdStdOut, _ := cmd.StdoutPipe()
s := bufio.NewScanner(cmdStdOut)
f, _ := os.Create("stdout.log")
w := bufio.NewWriter(f)
go func() {
for s.Scan(){
t := s.Text()
fmt.Println(t)
fmt.Fprint(w, t)
w.Flush()
}
}
Is there a more idiomatic way to do this that avoids clobbering Scan
and Flush
?