dongliao2241
2014-04-01 09:30
浏览 611
已采纳

如何将动态参数集传递给Go的命令exec.Command?

I came across a question on here relating to arguments being passed to Go's exec.Command function, and I was wondering if there was a way do pass these arguments dynamically? Here's some sample code from sed question:

package main

import "os/exec"

func main() {
    app := "echo"
    //app := "buah"

    arg0 := "-e"
    arg1 := "Hello world"
    arg2 := "
\tfrom"
    arg3 := "golang"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3)
    out, err := cmd.Output()

    if err != nil {
        println(err.Error())
        return
    }

    print(string(out))
}

So as you can see each arg is defined above as arg0, arg1, arg2 and arg3. They are passed into the Command function along with the actual command to run, in this case, the app var.

What if I had an array of arguments that always perhaps had an indeterministic count that I wanted to pass through. Is this possible?

图片转代码服务由CSDN问答提供 功能建议

我在这里遇到了一个与传递给Go的 exec.Command 的参数有关的问题 函数,我想知道是否有办法动态传递这些参数? 以下是sed问题的一些示例代码:

 包main 
 
import“ os / exec” 
 
func main(){
 app:=“ echo” \  n // app:=“ buah” 
 
 arg0:=“ -e” 
 arg1:=“ Hello world” 
 arg2:=“ 
 \ tfrom” 
 arg3:=“ golang” 
  
 cmd:= exec.Command(app,arg0,arg1,arg2,arg3)
 out,err:= cmd.Output()
 
 if err!= nil {
 println(err.Error()  )
 return 
} 
 
 print(string(out))
} 
   
 
 

因此您可以看到每个arg在上面都定义为< code> arg0 arg1 arg2 arg3 。 它们与实际要运行的命令一起传递到 Command 函数中,在本例中为 app 变量。

如果 我有各种各样的论据,可能总是不确定性地要传递给我。 可以吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duang5049 2014-04-01 09:35
    已采纳

    Like this:

    args := []string{"what", "ever", "you", "like"}
    cmd := exec.Command(app, args...)
    

    Have a look at the language and tutorial on golang.org.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题