Golang os/exec.Cmd.StderrPipe(), StdinPipe(), StdoutPipe() functions examples
package os
Golang os/exec.Cmd.StderrPipe(), StdinPipe(), StdoutPipe() functions usage examples
Example 1:
package main
import (
"bufio"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("/bin/echo", "Hello World")
stderr, err := cmd.StderrPipe()
if err != nil {
panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
err = cmd.Start()
if err != nil {
panic(err)
}
errorReader := bufio.NewReader(stderr) // read the stderr type io.ReadCloser
errorStr, _ := errorReader.ReadString('\n') // till next line and convert to String type
outputReader := bufio.NewReader(stdout)
outputStr, _ := outputReader.ReadString('\n')
// should be empty unless there is error
fmt.Printf("Error output : %v \n", errorStr)
// prints out the echo command result
fmt.Printf("Standard output : %v \n", outputStr)
}
Example 2:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("cat")
stdin, err := cmd.StdinPipe()
stdin.Write([]byte("Hello World!"))
stdin.Close()
if err != nil {
panic(err)
}
data, err := cmd.Output()
if err != nil {
panic(err)
}
for k, v := range data {
fmt.Printf("key : %v, value : %v \n", k, string(v))
}
}
Output :
key : 0, value : H
key : 1, value : e
key : 2, value : l
key : 3, value : l
key : 4, value : o
key : 5, value :
key : 6, value : W
key : 7, value : o
key : 8, value : r
key : 9, value : l
key : 10, value : d
key : 11, value : !
References :
http://golang.org/pkg/os/exec/#Cmd.StdoutPipe
Advertisement
Something interesting
Tutorials
+5.3k Swift : Convert string array to array example
+15.2k Golang : How to add color to string?
+9.7k Golang : Eroding and dilating image with OpenCV example
+11.8k Golang : GTK Input dialog box examples
+19.4k Golang : How to count the number of repeated characters in a string?
+8.3k Golang : Oanda bot with Telegram and RSI example
+10.4k Golang : Meaning of omitempty in struct's field tag
+17k Golang : Get input from keyboard
+5.8k Unix/Linux : How to test user agents blocked successfully ?
+14.1k Javascript : Prompt confirmation before exit
+14.3k Golang : Recombine chunked files example
+13.1k Golang : Handle or parse date string with Z suffix(RFC3339) example