Home >Backend Development >Golang >How to Reliably Capture and Save Golang `exec` Command Output to a File?

How to Reliably Capture and Save Golang `exec` Command Output to a File?

DDD
DDDOriginal
2024-12-02 10:19:13144browse

How to Reliably Capture and Save Golang `exec` Command Output to a File?

Capturing Command Output and Writing to File in Golang

When executing commands in Golang using the exec package, you may encounter situations where you want to capture the stdout and write it to a file. Here's a detailed guide on how to achieve this:

The initial approach involved creating a stdout pipe, setting up a writer, starting the command, and then copying the stdout into the file. However, this method occasionally resulted in an empty output file.

Thanks to insights from KirkMcDonald on the #go-nuts IRC channel, a simpler solution emerged. By assigning the output file directly to cmd.Stdout, the command's stdout can be written directly to the file. Here's the revised code:

package main

import (
    "os"
    "os/exec"
)

func main() {
    // Create the command to be executed
    cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")

    // Open the output file for writing
    outfile, err := os.Create("./out.txt")
    if err != nil {
        panic(err)
    }
    defer outfile.Close()

    // Assign the output file to the command's stdout
    cmd.Stdout = outfile

    // Start the command and wait for it to finish
    err = cmd.Start(); if err != nil {
        panic(err)
    }
    cmd.Wait()
}

With this improvement, the contents of the command's stdout will be written directly to the specified file. The file will no longer be empty, providing the expected output.

The above is the detailed content of How to Reliably Capture and Save Golang `exec` Command Output to a File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn