通过ENV VAR到exec.Command吗? [英] pass ENV VAR to exec.Command?

查看:61
本文介绍了通过ENV VAR到exec.Command吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为流行的命令行工具(ansible-playbook)编写go包装器,并且需要通过exec.Command调用传递参数.相当于bash:

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

以前,我只是使用os.Setenv导出MY_VAR,但是这会导致并行执行剧本出现问题.因此,我想在命令前传递var,以便每个调用对此var都有自己的值.

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.

我不太确定如何使用exec.Command来执行此操作,因为该函数的第一个参数是"command".有提示吗?

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

edit:我尝试使用Cmd结构的Env字段,但是它覆盖了所有环境变量.我有大量的配置集,我只想覆盖这个特定的环境变量.这不可能吗?

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??

推荐答案

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

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.

感谢godoc和开源!!

Thank goodness for godoc and open source!!

这篇关于通过ENV VAR到exec.Command吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆