From c55c33af52c5ed97c93ec67bf7373d095bcb957d Mon Sep 17 00:00:00 2001 From: Emmanuel Odeke Date: Wed, 14 Sep 2016 02:11:02 -0700 Subject: [PATCH] os/exec: add examples for CombinedOutput, StdinPipe, StderrPipe Updates #16360. Adds examples for: + CombinedOutput + StdinPipe + StderrPipe Change-Id: I19293e64b34ed9268da00e0519173a73bfbc2c10 Reviewed-on: https://go-review.googlesource.com/29150 Run-TryBot: Andrew Gerrand TryBot-Result: Gobot Gobot Reviewed-by: Andrew Gerrand --- src/os/exec/example_test.go | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/os/exec/example_test.go b/src/os/exec/example_test.go index 55eaac8abc..a38e2889e6 100644 --- a/src/os/exec/example_test.go +++ b/src/os/exec/example_test.go @@ -8,6 +8,8 @@ import ( "bytes" "encoding/json" "fmt" + "io" + "io/ioutil" "log" "os/exec" "strings" @@ -73,3 +75,51 @@ func ExampleCmd_StdoutPipe() { } fmt.Printf("%s is %d years old\n", person.Name, person.Age) } + +func ExampleCmd_StdinPipe() { + cmd := exec.Command("cat") + stdin, err := cmd.StdinPipe() + if err != nil { + log.Fatal(err) + } + + go func() { + defer stdin.Close() + io.WriteString(stdin, "values written to stdin are passed to cmd's standard input") + }() + + out, err := cmd.CombinedOutput() + if err != nil { + log.Fatal(err) + } + + fmt.Printf("%s\n", out) +} + +func ExampleCmd_StderrPipe() { + cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") + stderr, err := cmd.StderrPipe() + if err != nil { + log.Fatal(err) + } + + if err := cmd.Start(); err != nil { + log.Fatal(err) + } + + slurp, _ := ioutil.ReadAll(stderr) + fmt.Printf("%s\n", slurp) + + if err := cmd.Wait(); err != nil { + log.Fatal(err) + } +} + +func ExampleCmd_CombinedOutput() { + cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") + stdoutStderr, err := cmd.CombinedOutput() + if err != nil { + log.Fatal(err) + } + fmt.Printf("%s\n", stdoutStderr) +}