猿问

带有可变参数的 exec.Command

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


a := fileName

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

我不确定如何解决这个问题,我想我需要在通过它之前完全形成论点,但我也在努力解决这个问题。我不知道该怎么做:


a := fileName

arg := "/path/to/"a

exec.Command("command", arg).Output()


喵喔喔
浏览 336回答 2
2回答

HUX布斯

在 Go 中,字符串与+,exec.Command("command", "/path/to/" + a)您还可以使用格式化功能exec.Command("command", fmt.Sprintf("/path/to/%s", a))但在这种情况下,它可能更适合使用filepath.Joindir := "/path/to/"exec.Command     ("command", filepath.Join(dir, a))

呼啦一阵风

我通常使用这种方法:a := fileNamecmdArgs := []string{"/path/to/" + a, "morearg"}out, err := exec.Command("command", cmdArgs...).Output()
随时随地看视频慕课网APP

相关分类

Go
我要回答