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
+13.5k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+4.7k PHP : Shuffle to display different content or advertisement
+3.8k Golang : How to detect if a sentence ends with a punctuation?
+13k Golang : Get future or past hours, minutes or seconds
+9.7k Golang : Query string with space symbol %20 in between
+7.7k Golang : Create S3 bucket with official aws-sdk-go package
+6.5k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+10.1k Golang : Google Drive API upload and rename example
+5.2k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+14.4k Golang : Generate MD5 checksum of a file
+4.5k Golang : Muxing with Martini example