Golang : Capture stdout of a child process and act according to the result




Let say you want to execute a shell command of a child process in your main program and want to capture the output of the child process via stdout pipe. This tutorial will show you how to execute a child process, capture the output, convert the output into a slice and then process according to the child process output.

Here it is :

 package main

 import (
 "bufio"
 "fmt"
 "io"
 "os"
 "os/exec"
 "time"
 )

 func handleError(err error) {
 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }
 }

 func main() {
 // ls -la command might not be the best because it will always return something
 // and cause the lenght of allText(below) to be more than 1

 cmd := exec.Command("ls", "-la")

 // capture the output and error pipes
 stdout, err := cmd.StdoutPipe()
 handleError(err)
 stderr, err := cmd.StderrPipe()
 handleError(err)

 // Start digging !
 err = cmd.Start()
 handleError(err)

 // Don't let main() exit before our command has finished running
 defer cmd.Wait() // Doesn't block

 // Non-blockingly echo command output to terminal
 //go io.Copy(os.Stdout, stdout) //  <---- commented out because we will print out with buff.Scan()
 go io.Copy(os.Stderr, stderr)

 // here is where we want to know the child output
 // and depending on the output, display different result
 // in the main program

 buff := bufio.NewScanner(stdout)
 var allText []string

 for buff.Scan() {
 allText = append(allText, buff.Text()+"\n")
 }

 if len(allText) > 1 {
 // if the allText has value, then do a count down
 ticker := time.Tick(time.Second)
 fmt.Println("Scanner detected something. Counting down to finding the biggest treasure...\n\n")

 for i := 9; i >= 0; i-- {
 <-ticker
 //fmt.Printf("\x0cOn 10/%d", i) // use \x0c for play.golang.org
 fmt.Printf("\rstill counting the dig 10/%d", i) // use \r if you are running this in terminal

 }
 fmt.Println("\nFinished digging.\n")

 } else {
 fmt.Println("Scanner returns zero. Nothing to do")
 }

 }




By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement