【问题标题】:exec.Command with variable arguments带有可变参数的 exec.Command
【发布时间】:2016-08-30 18:20:09
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: variables go exec


    【解决方案1】:

    在 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))
    

    【讨论】:

    • Jim,感谢您提供完整的选项列表。我同意,filepath.Join 似乎是最合适的解决方案。
    【解决方案2】:

    我通常使用这种方法:

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

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      相关资源
      最近更新 更多