exec.Command 可变参数

exec.Command with variable arguments

我正在尝试将参数传递给 exec.Command。 该参数的 部分是一个变量。

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

我不确定如何处理这个问题,我想我需要在通过它之前完整地形成论点,但我也在为这个选项而苦苦挣扎。我不确定如何做类似的事情:

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

在 Go 中,字符串与 +

连接
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))

我通常使用这种方法:

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