【发布时间】:2017-04-06 01:04:38
【问题描述】:
我希望我的方法接收一个以字符串形式执行的命令。如果输入字符串有空格,如何拆分成cmd、args for os.exec?
文档说要创建我的 Exec.Cmd 结构,如
cmd := exec.Command("tr", "a-z", "A-Z")
这很好用:
a := string("ifconfig")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // prints ifconfig output
这失败了:
a := string("ifconfig -a")
cmd := exec.Command(a)
output, err := cmd.CombinedOutput()
fmt.Println(output) // 'ifconfig -a' not found
我尝试了strings.Split(a),但收到一条错误消息:不能在exec.Command 的参数中使用(type []string) 作为类型字符串
【问题讨论】:
-
您错误地使用了 strings.Split() golang.org/pkg/strings/#Split 您需要提供一个分隔符。所以.. strings.Split(a, " ") 在单个空格上拆分,其次,您不能拆分切片,因为它已经拆分,因此您的变量“a”已经是切片,而不是字符串。最后,您还可以定义切片而不是拆分字符串。 a := []string{"inconfig", "a"}.
-
如果参数包含空格,这不会中断吗?
标签: go