go - In golang how can I write the stdout of an exec.Cmd to a file? -
i trying run shell command, capture stdout , write output file. however, seem missing few steps, file trying write empty when program exists. how can capture stdout of command , write file?
package main import ( "bufio" "io" "os" "os/exec" ) func main() { cmd := exec.command("echo", "'what heck up'") // open out file writing outfile, err := os.create("./out.txt") if err != nil { panic(err) } defer outfile.close() stdoutpipe, err := cmd.stdoutpipe() if err != nil { panic(err) } writer := bufio.newwriter(outfile) err = cmd.start() if err != nil { panic(err) } go io.copy(writer, stdoutpipe) cmd.wait() }
you need flush writer. add following:
writer := bufio.newwriter(outfile) defer writer.flush()
Comments
Post a Comment