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
+9.8k Golang : Read file and convert content to string
+6.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+18.5k Golang : How to make function callback or pass value from function as parameter?
+20.4k Golang : Convert date string to variants of time.Time type examples
+13k Facebook PHP getUser() returns 0
+4.6k Google : Block or disable caching of your website content
+7.4k Golang : Test if an input is an Armstrong number example
+28.9k Golang : Save map/struct to JSON or XML file
+6.5k Golang : Calculate pivot points for a cross
+23.1k Find and replace a character in a string in Go
+10.2k Golang : Allow Cross-Origin Resource Sharing request
+25.4k Golang : How to read integer value from standard input ?