我正在尝试运行shell命令,捕获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() }
您需要冲洗编写器。添加以下内容:
writer := bufio.NewWriter(outfile) defer writer.Flush()