我正在尝试运行 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()
}
慕哥9229398
BIG阳
相关分类