dsiuy42084
2013-09-24 16:20
浏览 726
已采纳

在golang中,如何将exec.Cmd的标准输出写入文件?

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()
}

图片转代码服务由CSDN问答提供 功能建议

我正在尝试运行shell命令,捕获stdout并将该输出写入文件。 但是,我似乎缺少了一些步骤,因为当程序存在时,我要写入的文件为空。 如何捕获命令的标准输出并将其写入文件?

 包main 
 
import(
“ bufio” 
“ io” 
“  os“ 
” os / exec“ 
)
 
func main(){
 
 cmd:= exec.Command(” echo“,”'到底发生了什么'“)
 
 /  /打开要写入的输出文件
输出文件,err:= os.Create(“ ./ out.txt”)
如果err!= nil {
 panic(err)
} 
延迟outfile.Close(  )
 
 stdoutPipe,错误:= cmd.StdoutPipe()
如果错误!= nil {
 panic(err)
} 
 
 writer:= bufio.NewWriter(outfile)
 
 err  = cmd.Start()
,如果出错!= nil {
 panic(err)
} 
 
 go io.Copy(writer,stdoutPipe)
 cmd.Wait()
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题