概述
本文实例讲述了Go语言执行系统命令行命令的方法。分享给大家供大家参考。具体如下:
执行Go代码时可以附加参数,包括要执行的命令和给命令的参数
复制代码 代码如下:
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)
}
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)
}
希望本文所述对大家的Go语言程序设计有所帮助。
最后
以上就是如意戒指为你收集整理的Go语言执行系统命令行命令的方法的全部内容,希望文章能够帮你解决Go语言执行系统命令行命令的方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复