Go语言执行系统命令行命令的方法
本文实例讲述了Go语言执行系统命令行命令的方法。分享给大家供大家参考。具体如下:
执行Go代码时可以附加参数,包括要执行的命令和给命令的参数
packagemain import( "os" "os/exec" "fmt" "flag" "strings" ) funcmain(){ command:=flag.String("cmd","pwd","Setthecommand.") args:=flag.String("args","","Settheargs.(separatedbyspaces)") flag.Usage=func(){ fmt.Fprintf(os.Stderr,"Usage:%s[-cmd<command>][-args<thearguments(separatedbyspaces)>]\n",os.Args[0]) flag.PrintDefaults() } flag.Parse() fmt.Println("Command:",*command) fmt.Println("Arguments:",*args) varargArray[]string if*args!=""{ argArray=strings.Split(*args,"") }else{ argArray=make([]string,0) } cmd:=exec.Command(*command,argArray...) buf,err:=cmd.Output() iferr!=nil{ fmt.Fprintf(os.Stderr,"Thecommandfailedtoperform:%s(Command:%s,Arguments:%s)",err,*command,*args) return } fmt.Fprintf(os.Stdout,"Result:%s",buf) }
希望本文所述对大家的Go语言程序设计有所帮助。