2016-08-30 233 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()