Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...