pass ENV VAR to exec.Command?

huangapple go评论80阅读模式
英文:

pass ENV VAR to exec.Command?

问题

我正在为一个流行的命令行工具(ansible-playbook)编写一个Go语言封装,并且我需要通过exec.Command调用传递一个参数。在bash中的等效方式是:

MY_VAR=some_value ansible-playbook -i custom-inventory playbook.yml

之前我只是使用os.Setenv导出MY_VAR,但这会导致并行执行playbook时出现问题。所以我想在命令前面传递这个变量,这样每个调用都有自己的变量值。

我不太确定如何在exec.Command中实现这一点,因为该函数的第一个参数是"command"。有什么建议吗?

编辑:我尝试过使用Cmd结构体的Env字段,但那会覆盖所有环境变量。我设置了大量的配置,我只想覆盖这一个特定的环境变量。这不可能吗?

英文:

I'm writing a go wrapper for a popular command line tool (ansible-playbook) and I need to pass a parameter through with the exec.Command call. The bash equivalent would be:

MY_VAR=some_value ansible-playbook -i custom-inventory playbook.yml

Previously I was just exporting MY_VAR using os.Setenv, but that causes problems for parallel executions of the playbook. So I want to pass the var in front of the command so that each call has it's own value for this var.

I'm not really sure how to do this with exec.Command since the first parameter to that function is "command". Any tips?

edit: I have tried using the Env field of the Cmd struct but that overrides all environment variables. I have a significant amount of configuration set and I would just like to override this one specific environment variable. Is this not possible??

答案1

得分: 113

对于那些想要解决方案的人:

    cmd := exec.Command("ansible-playbook", args...)
    cmd.Env = os.Environ()
    cmd.Env = append(cmd.Env, "MY_VAR=some_value")

将保留现有的环境,并写入您想要的一个值。

感谢godoc和开源!

英文:

For those wondering for the solution:

    cmd := exec.Command("ansible-playbook", args...)
    cmd.Env = os.Environ()
    cmd.Env = append(cmd.Env, "MY_VAR=some_value")

Will preserve the existing environment and then write the one value that you want.

Thank goodness for godoc and open source!!

huangapple
  • 本文由 发表于 2016年12月14日 09:00:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/41133115.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定