我试图运行一个shell命令,捕获stdout并将该输出写入一个文件。但是,我似乎缺少几个步骤,因为当程序存在时,我正在写的文件是空的。如何捕获命令的stdout并将其写入文件?
package main import ( "bufio" "io" "os" "os/exec" ) func main() { cmd := exec.Command("echo","'WHAT THE HECK IS UP'") // open the out file for 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() }