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
+8.8k Golang : Inject/embed Javascript before sending out to browser example
+18.3k Golang : Find IP address from string
+7.2k Golang : Individual and total number of words counter example
+5.6k Golang : Find change in a combination of coins example
+16.9k Golang : Covert map/slice/array to JSON or XML format
+50.6k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+10.3k Golang : Select region of interest with mouse click and crop from image
+17.8k Golang : Convert IPv4 address to decimal number(base 10) or integer
+37.2k Upload multiple files with Go
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+4.5k Linux/MacOSX : How to symlink a file?
+6.1k Golang : Test input string for unicode example