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
Tutorials
+7.9k Golang : Auto-generate reply email with text/template package
+7.1k Golang : Check to see if *File is a file or directory
+10.8k Golang : Web routing/multiplex example
+11.5k Golang : Verify Linux user password again before executing a program example
+5.7k Golang : Use NLP to get sentences for each paragraph example
+16.1k Golang : Test floating point numbers not-a-number and infinite example
+31.1k Golang : How to convert(cast) string to IP address?
+15.3k Golang : How to convert(cast) IP address to string?
+7.8k Golang : Get all countries phone codes
+18.9k Golang : Get host name or domain name from IP address
+7.4k Golang : Command line ticker to show work in progress
+6.2k PHP : Proper way to get UTF-8 character or string length