您的代码失败,因为 exec.Command 期望命令参数与实际的命令名称分开. strings.Split 签名( https://golang.org/pkg/strings/#Split ): func Split(s,sep string)[] string 您试图实现的目标: 命令:= strings.Split("ifconfig -a",")如果len(command)<2 {//TODO:处理错误}cmd:= exec.Command(命令[0],命令[1:] ...)stdoutStderr,err:= cmd.CombinedOutput()如果err!= nil {//TODO:更优雅地处理错误log.Fatal(错误)}//对输出做一些事情fmt.Printf(%s \ n",stdoutStderr) I want my method to receive a command to exec as a string. If the input string has spaces, how do I split it into cmd, args for os.exec?The documentation says to create my Exec.Cmd struct likecmd := exec.Command("tr", "a-z", "A-Z")This works fine:a := string("ifconfig")cmd := exec.Command(a)output, err := cmd.CombinedOutput()fmt.Println(output) // prints ifconfig outputThis fails:a := string("ifconfig -a")cmd := exec.Command(a)output, err := cmd.CombinedOutput()fmt.Println(output) // 'ifconfig -a' not foundI tried strings.Split(a), but receive an error message: cannot use (type []string) as type string in argument to exec.Command 解决方案 Please, check out:https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutputYour code fails because exec.Command expects command arguments to be separated from actual command name.strings.Split signature (https://golang.org/pkg/strings/#Split):func Split(s, sep string) []stringWhat you tried to achieve:command := strings.Split("ifconfig -a", " ")if len(command) < 2 { // TODO: handle error}cmd := exec.Command(command[0], command[1:]...)stdoutStderr, err := cmd.CombinedOutput()if err != nil { // TODO: handle error more gracefully log.Fatal(err)}// do something with outputfmt.Printf("%s\n", stdoutStderr) 这篇关于如何使用带空格的字符串创建os.exec Command结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-23 19:15