我希望我的方法能够以exec作为字符串接收命令。如果输入字符串有空格,我如何将它分割为cmd,args为os.exec?如何使用空格字符串创建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(一),但收到错误消息:不能使用(类型[]字符串)作为参数中的类型字符串给exec.Command
您使用strings.Split()不正确golang.org/pkg/strings/#拆分你需要提供一个分隔符。 so .. strings.Split(a,“”)在一个空间上分割,其次,你不能分割一个切片,因为它已经被分割,所以你的变量“a”已经是一个切片,而不是一个字符串。最后,你也可以定义你的切片而不是分割字符串。 a:= [] string {“inconfig”,“a”}。 – reticentroot