Capture the outout of an external program



examples/capture-external/capture_external.go
package main

import (
    "bytes"
    "fmt"
    "log"
    "os/exec"
)

func main() {
    cmd := exec.Command("go", "run", "examples/external/external.go", "23")
    //cmd := exec.Command("ls", "xxx")
    var stdout, stderr bytes.Buffer
    cmd.Stdout = &stdout
    cmd.Stderr = &stderr
    err := cmd.Run()
    fmt.Println("-------")
    fmt.Println(stdout.String())
    fmt.Println("-------")
    fmt.Println(stderr.String())
    fmt.Println("-------")
    fmt.Println(cmd.ProcessState.String() == "exit status 2")
    fmt.Println(cmd.ProcessState)
    fmt.Println("-------")
    if err != nil {
        log.Fatal(err)
    }
}

examples/external/external.go
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Fprintln(os.Stderr, "Needs to get the expected exit code as a parameter")
        os.Exit(1)
    }
    exit_code, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Fprintln(os.Stderr, "Expected integer on the command line")
        os.Exit(-1)
    }

    fmt.Println("To STDOUT")
    fmt.Fprintln(os.Stderr, "To STDERR")
    os.Exit(exit_code)
}