Skip to content

Commit c55c33a

Browse files
odeke-emadg
authored andcommitted
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 <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Andrew Gerrand <[email protected]>
1 parent 1bd91d4 commit c55c33a

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/os/exec/example_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"bytes"
99
"encoding/json"
1010
"fmt"
11+
"io"
12+
"io/ioutil"
1113
"log"
1214
"os/exec"
1315
"strings"
@@ -73,3 +75,51 @@ func ExampleCmd_StdoutPipe() {
7375
}
7476
fmt.Printf("%s is %d years old\n", person.Name, person.Age)
7577
}
78+
79+
func ExampleCmd_StdinPipe() {
80+
cmd := exec.Command("cat")
81+
stdin, err := cmd.StdinPipe()
82+
if err != nil {
83+
log.Fatal(err)
84+
}
85+
86+
go func() {
87+
defer stdin.Close()
88+
io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")
89+
}()
90+
91+
out, err := cmd.CombinedOutput()
92+
if err != nil {
93+
log.Fatal(err)
94+
}
95+
96+
fmt.Printf("%s\n", out)
97+
}
98+
99+
func ExampleCmd_StderrPipe() {
100+
cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
101+
stderr, err := cmd.StderrPipe()
102+
if err != nil {
103+
log.Fatal(err)
104+
}
105+
106+
if err := cmd.Start(); err != nil {
107+
log.Fatal(err)
108+
}
109+
110+
slurp, _ := ioutil.ReadAll(stderr)
111+
fmt.Printf("%s\n", slurp)
112+
113+
if err := cmd.Wait(); err != nil {
114+
log.Fatal(err)
115+
}
116+
}
117+
118+
func ExampleCmd_CombinedOutput() {
119+
cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
120+
stdoutStderr, err := cmd.CombinedOutput()
121+
if err != nil {
122+
log.Fatal(err)
123+
}
124+
fmt.Printf("%s\n", stdoutStderr)
125+
}

0 commit comments

Comments
 (0)