The way the Go language executes system command line commands
- 2020-05-19 05:00:26
- OfStack
This article illustrates how the Go language executes system command line commands. Share with you for your reference. The details are as follows:
The Go code can be executed with additional arguments, including the command to execute and the arguments to the command
package main
import (
"os"
"os/exec"
"fmt"
"flag"
"strings"
)
func main() {
command := flag.String("cmd", "pwd", "Set the command.")
args := flag.String("args", "", "Set the args. (separated by spaces)")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [-cmd <command>] [-args <the arguments (separated by spaces)>]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
fmt.Println("Command: ", *command)
fmt.Println("Arguments: ", *args)
var argArray []string
if *args != "" {
argArray = strings.Split(*args, " ")
} else {
argArray = make([]string, 0)
}
cmd := exec.Command(*command, argArray...)
buf, err := cmd.Output()
if err != nil {
fmt.Fprintf(os.Stderr, "The command failed to perform: %s (Command: %s, Arguments: %s)", err, *command, *args)
return
}
fmt.Fprintf(os.Stdout, "Result: %s", buf)
}
I hope this article has been helpful to your programming of Go language.