Go语言执行系统命令行命令的方法
程序员文章站
2022-11-15 22:40:48
本文实例讲述了go语言执行系统命令行命令的方法。分享给大家供大家参考。具体如下:
执行go代码时可以附加参数,包括要执行的命令和给命令的参数
复制代码 代码如下:pac...
本文实例讲述了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语言程序设计有所帮助。
下一篇: Python3爬虫(十一) 爬虫与反爬虫