Black Lives Matter. Support the Equal Justice Initiative.

Source file src/os/exec/example_test.go

Documentation: os/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  	"context"
    10  	"encoding/json"
    11  	"fmt"
    12  	"io"
    13  	"log"
    14  	"os"
    15  	"os/exec"
    16  	"strings"
    17  	"time"
    18  )
    19  
    20  func ExampleLookPath() {
    21  	path, err := exec.LookPath("fortune")
    22  	if err != nil {
    23  		log.Fatal("installing fortune is in your future")
    24  	}
    25  	fmt.Printf("fortune is available at %s\n", path)
    26  }
    27  
    28  func ExampleCommand() {
    29  	cmd := exec.Command("tr", "a-z", "A-Z")
    30  	cmd.Stdin = strings.NewReader("some input")
    31  	var out bytes.Buffer
    32  	cmd.Stdout = &out
    33  	err := cmd.Run()
    34  	if err != nil {
    35  		log.Fatal(err)
    36  	}
    37  	fmt.Printf("in all caps: %q\n", out.String())
    38  }
    39  
    40  func ExampleCommand_environment() {
    41  	cmd := exec.Command("prog")
    42  	cmd.Env = append(os.Environ(),
    43  		"FOO=duplicate_value", // ignored
    44  		"FOO=actual_value",    // this value is used
    45  	)
    46  	if err := cmd.Run(); err != nil {
    47  		log.Fatal(err)
    48  	}
    49  }
    50  
    51  func ExampleCmd_Output() {
    52  	out, err := exec.Command("date").Output()
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  	fmt.Printf("The date is %s\n", out)
    57  }
    58  
    59  func ExampleCmd_Run() {
    60  	cmd := exec.Command("sleep", "1")
    61  	log.Printf("Running command and waiting for it to finish...")
    62  	err := cmd.Run()
    63  	log.Printf("Command finished with error: %v", err)
    64  }
    65  
    66  func ExampleCmd_Start() {
    67  	cmd := exec.Command("sleep", "5")
    68  	err := cmd.Start()
    69  	if err != nil {
    70  		log.Fatal(err)
    71  	}
    72  	log.Printf("Waiting for command to finish...")
    73  	err = cmd.Wait()
    74  	log.Printf("Command finished with error: %v", err)
    75  }
    76  
    77  func ExampleCmd_StdoutPipe() {
    78  	cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
    79  	stdout, err := cmd.StdoutPipe()
    80  	if err != nil {
    81  		log.Fatal(err)
    82  	}
    83  	if err := cmd.Start(); err != nil {
    84  		log.Fatal(err)
    85  	}
    86  	var person struct {
    87  		Name string
    88  		Age  int
    89  	}
    90  	if err := json.NewDecoder(stdout).Decode(&person); err != nil {
    91  		log.Fatal(err)
    92  	}
    93  	if err := cmd.Wait(); err != nil {
    94  		log.Fatal(err)
    95  	}
    96  	fmt.Printf("%s is %d years old\n", person.Name, person.Age)
    97  }
    98  
    99  func ExampleCmd_StdinPipe() {
   100  	cmd := exec.Command("cat")
   101  	stdin, err := cmd.StdinPipe()
   102  	if err != nil {
   103  		log.Fatal(err)
   104  	}
   105  
   106  	go func() {
   107  		defer stdin.Close()
   108  		io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")
   109  	}()
   110  
   111  	out, err := cmd.CombinedOutput()
   112  	if err != nil {
   113  		log.Fatal(err)
   114  	}
   115  
   116  	fmt.Printf("%s\n", out)
   117  }
   118  
   119  func ExampleCmd_StderrPipe() {
   120  	cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
   121  	stderr, err := cmd.StderrPipe()
   122  	if err != nil {
   123  		log.Fatal(err)
   124  	}
   125  
   126  	if err := cmd.Start(); err != nil {
   127  		log.Fatal(err)
   128  	}
   129  
   130  	slurp, _ := io.ReadAll(stderr)
   131  	fmt.Printf("%s\n", slurp)
   132  
   133  	if err := cmd.Wait(); err != nil {
   134  		log.Fatal(err)
   135  	}
   136  }
   137  
   138  func ExampleCmd_CombinedOutput() {
   139  	cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
   140  	stdoutStderr, err := cmd.CombinedOutput()
   141  	if err != nil {
   142  		log.Fatal(err)
   143  	}
   144  	fmt.Printf("%s\n", stdoutStderr)
   145  }
   146  
   147  func ExampleCommandContext() {
   148  	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
   149  	defer cancel()
   150  
   151  	if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
   152  		// This will fail after 100 milliseconds. The 5 second sleep
   153  		// will be interrupted.
   154  	}
   155  }
   156  

View as plain text