本文介绍了在golang中,如何将exec.Cmd的stdout写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试运行一个shell命令,捕获stdout并将输出写入一个文件。但是,我似乎错过了几个步骤,因为我正在写的文件是空的,当程序存在。如何捕获命令的stdout并将其写入文件? package main
导入(
bufio
io
os
os / exec
)
func main(){
cmd:= exec.Command(echo,'HECK IS UP)
//打开输出文件
outfile ,err:= os.Create(./out.txt)
if err!= nil {
panic(err)
}
defer outfile.Close()
stdoutPipe,err:= cmd.StdoutPipe()
if err!= nil {
panic(err)
}
作者: = bufio.NewWriter(outfile)
err = cmd.Start()
if err!= nil {
panic(err)
}
go io.Copy(writer,stdoutPipe)
cmd.Wait()
}
解决方案
您需要刷新作者。添加以下内容:
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ b
I am trying to run a shell command, capture stdout and write that output to a file. However, I seem to be missing a few steps, as the file I am trying to write is empty when the program exists. How can I capture the stdout of the command and write that to a file?
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()
}
解决方案
You need to flush the writer. Add the following:
writer := bufio.NewWriter(outfile)
defer writer.Flush()
这篇关于在golang中,如何将exec.Cmd的stdout写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!