Home | History | Annotate | Download | only in exec
      1 // Copyright 2012 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package exec_test
      6 
      7 import (
      8 	"bytes"
      9 	"encoding/json"
     10 	"fmt"
     11 	"log"
     12 	"os/exec"
     13 	"strings"
     14 )
     15 
     16 func ExampleLookPath() {
     17 	path, err := exec.LookPath("fortune")
     18 	if err != nil {
     19 		log.Fatal("installing fortune is in your future")
     20 	}
     21 	fmt.Printf("fortune is available at %s\n", path)
     22 }
     23 
     24 func ExampleCommand() {
     25 	cmd := exec.Command("tr", "a-z", "A-Z")
     26 	cmd.Stdin = strings.NewReader("some input")
     27 	var out bytes.Buffer
     28 	cmd.Stdout = &out
     29 	err := cmd.Run()
     30 	if err != nil {
     31 		log.Fatal(err)
     32 	}
     33 	fmt.Printf("in all caps: %q\n", out.String())
     34 }
     35 
     36 func ExampleCmd_Output() {
     37 	out, err := exec.Command("date").Output()
     38 	if err != nil {
     39 		log.Fatal(err)
     40 	}
     41 	fmt.Printf("The date is %s\n", out)
     42 }
     43 
     44 func ExampleCmd_Start() {
     45 	cmd := exec.Command("sleep", "5")
     46 	err := cmd.Start()
     47 	if err != nil {
     48 		log.Fatal(err)
     49 	}
     50 	log.Printf("Waiting for command to finish...")
     51 	err = cmd.Wait()
     52 	log.Printf("Command finished with error: %v", err)
     53 }
     54 
     55 func ExampleCmd_StdoutPipe() {
     56 	cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
     57 	stdout, err := cmd.StdoutPipe()
     58 	if err != nil {
     59 		log.Fatal(err)
     60 	}
     61 	if err := cmd.Start(); err != nil {
     62 		log.Fatal(err)
     63 	}
     64 	var person struct {
     65 		Name string
     66 		Age  int
     67 	}
     68 	if err := json.NewDecoder(stdout).Decode(&person); err != nil {
     69 		log.Fatal(err)
     70 	}
     71 	if err := cmd.Wait(); err != nil {
     72 		log.Fatal(err)
     73 	}
     74 	fmt.Printf("%s is %d years old\n", person.Name, person.Age)
     75 }
     76