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

在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()
}
  • 写回答

3条回答 默认 最新

  • dtbrd80422 2013-09-24 16:27
    关注

    You need to flush the writer. Add the following:

        writer := bufio.NewWriter(outfile)
        defer writer.Flush()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办