1
0
mirror of https://github.com/golang/go synced 2024-11-18 13:54:59 -07:00

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 <adg@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Andrew Gerrand <adg@golang.org>
This commit is contained in:
Emmanuel Odeke 2016-09-14 02:11:02 -07:00 committed by Andrew Gerrand
parent 1bd91d4ccc
commit c55c33af52

View File

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