In golang how can I write the stdout of an exec.Cmd to a file?

前端 未结 3 1367
梦谈多话
梦谈多话 2020-12-23 18:47

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

相关标签:
3条回答
  • 2020-12-23 19:05

    Thanks to KirkMcDonald on the #go-nuts irc channel, I solved this by assigning the output file to cmd.Stdout, which means that stdout writes directly to the file. It looks like this:

    package main
    
    import (
        "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()
        cmd.Stdout = outfile
    
        err = cmd.Start(); if err != nil {
            panic(err)
        }
        cmd.Wait()
    }
    
    0 讨论(0)
  • 2020-12-23 19:08

    You can also use:

    cmd.Stdout = os.Stdout
    

    which will redirect all cmd output to the OS' standard output.

    0 讨论(0)
  • 2020-12-23 19:14

    You need to flush the writer. Add the following:

        writer := bufio.NewWriter(outfile)
        defer writer.Flush()
    
    0 讨论(0)
提交回复
热议问题