Golang : Capture text return from exec function example
Problem:
You want to capture the text result return by exec function. How to do that?
Solution:
The code example below demonstrates how to capture the text result returns by the os/exec function. What the code does is to prepare in advance a pipe(io.ReadCloser) first before executing the exec program to capture the standard output. Then the value will be stored(appended) in a string slice for display at the end of the program.
Here you go!
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
)
func handleError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func main() {
cmd := exec.Command("whoami")
// capture the output and error pipes
stdout, err := cmd.StdoutPipe()
handleError(err)
err = cmd.Start()
handleError(err)
defer cmd.Wait()
buff := bufio.NewScanner(stdout)
var returnText []string
for buff.Scan() {
returnText = append(returnText, buff.Text())
}
fmt.Println(returnText)
}
Happy coding!
References:
See also : Golang : Capture stdout of a child process and act according to the result
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
+19.6k Golang : Create and resolve(read) symbolic links
+11.2k Golang : Validate email address
+27.9k Golang : missing Git command
+12.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+8.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+14.9k Golang : convert string or integer to big.Int type
+22.1k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+14.7k Golang : Generate universally unique identifier(UUID) example
+6.3k Golang : Scanf function weird error in Windows
+6.3k Android Studio : AlertDialog to get user attention example
+6.8k Golang : Sort words with first uppercase letter
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday