2016-08-30 230 views
0

我试图将一个参数传递给一个exec.Command。 该参数的第部分是变量。GO - 具有可变参数的exec.Command

a := fileName 
exec.Command("command", "/path/to/"a).Output() 

我不知道如何解决这个,我想我需要完全形成之前的说法,即使我通过它,但我也有这个选项挣扎。我不知道怎么做这样的事情:

a := fileName 
arg := "/path/to/"a 
exec.Command("command", arg).Output() 

回答

2

在围棋字符串连与+

exec.Command("command", "/path/to/" + a) 

你也可以使用格式化功能

exec.Command("command", fmt.Sprintf("/path/to/%s", a)) 

但在这可能更适合使用filepath.Join

dir := "/path/to/" 
exec.Command("command", filepath.Join(dir, a)) 
+0

吉姆, 感谢的选项彻底列表。我同意,filepath.Join似乎是最合适的解决方案。 –

0

我通常使用这种方法:

a := fileName 
cmdArgs := []string{"/path/to/" + a, "morearg"} 
out, err := exec.Command("command", cmdArgs...).Output()