2017-04-06 67 views
4

我希望我的方法能够以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

+0

您使用strings.Split()不正确golang.org/pkg/strings/#拆分你需要提供一个分隔符。 so .. strings.Split(a,“”)在一个空间上分割,其次,你不能分割一个切片,因为它已经被分割,所以你的变量“a”已经是一个切片,而不是一个字符串。最后,你也可以定义你的切片而不是分割字符串。 a:= [] string {“inconfig”,“a”}。 – reticentroot

回答

5

请检查: https://golang.org/pkg/os/exec/#example_Cmd_CombinedOutput

您的代码会失败,因为exec.Command需要命令参数与实际分开命令名称

strings.Split签名(https://golang.org/pkg/strings/#Split):

func Split(s, sep string) []string 

你想实现什么:

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 output 
fmt.Printf("%s\n", stdoutStderr) 
+0

'exec.Command(command ...)'更简单IMO ;-) – kostix

+2

@kostix不,它不起作用。文档说:'func Command(name string,arg ... string)* Cmd' - 因此你必须单独传递第一个参数(命令名)。否则,你会产生错误:'没有足够的参数调用exec.Command'。我在@Mark的答案中指出了这一点,因为他犯了同样的错误。 – mwarzynski

+0

傻我 - 感谢您的纠正! ;-) – kostix

4
args := strings.Fields("ifconfig -a ") 
exec.Command(args[0], args[1:]...) 

strings.Fields()上的空白分裂,并返回一个切片

...扩展片分为单独的字符串参数

+1

执行你的代码会产生一个错误:'调用exec.Command时没有足够的参数'。 您需要单独传递命令名称。 – mwarzynski

+0

谢谢@mwarzynski,更新。 – Mark

相关问题