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

http://golang.org/pkg/os/exec/#Cmd.StdinPipe

http://golang.org/pkg/os/exec/#Cmd.StderrPipe

Advertisement