-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
65 lines (58 loc) · 2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"fmt"
"io/ioutil"
"os/exec"
)
/*
Sometimes our Go programs need to spawn other, non-Go processes.
For example, the syntax highlighting on this site is implemented
by spawning a pygmentize process from a Go program.
Let’s look at a few examples of spawning processes from Go.
*/
// Process function to illustrate how to launch process in go.
func main() {
// We’ll start with a simple command that takes no arguments
// or input and just prints something to stdout. The exec.Command
// helper creates an object to represent this external process.
dateCmd := exec.Command("date")
// .Output is another helper that handles the common case of
// running a command, waiting for it to finish, and collecting
// its output. If there were no errors,
// dateOut will hold bytes with the date info.
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> Date")
fmt.Println(string(dateOut))
// Next we’ll look at a slightly more involved case where
// we pipe data to the external process on its stdin and
// collect the results from its stdout.
grepCmd := exec.Command("grep", "hello")
// Here we explicitly grab input/output pipes,
// start the process, write some input to it,
// read the resulting output,
// and finally wait for the process to exit.
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("hello grep\ngoodbye grep"))
grepIn.Close()
grepBytes, _ := ioutil.ReadAll(grepOut)
grepCmd.Wait()
fmt.Println("> grep hello")
fmt.Println(string(grepBytes))
// Note that when spawning commands we need to provide an
// explicitly delineated command and argument array,
// vs. being able to just pass in one command-line string.
// If you want to spawn a full command with a string,
// you can use bash’s -c option:
lsCmd := exec.Command("bash", "-c", "kubectl get nodes")
lsOut, err := lsCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> kubectl get nodes")
fmt.Println(string(lsOut))
}