Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Capture the outout of an external program

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)
	}
}
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)
}