dongxun3777 2019-09-04 21:28
浏览 123

Golang-从COBRA命令内部设置环境变量

In vanilla go, it seems pretty trivial to set an environment variable. The os library has a Setenv function that should get the job done. I'm running into trouble doing that inside of a cobra command. Is there a simple way that I'm missing, or is this functionality not supported at this point?

Example of what I'm trying to do:

package main

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
    "github.com/spf13/pflag"

    "k8s.io/cli-runtime/pkg/genericclioptions"
)

func main() {
    flags := pflag.NewFlagSet("ex-com", pflag.ExitOnError)
    pflag.CommandLine = flags

    root := newCmdEx(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})
    if err := root.Execute(); err != nil {
        fmt.Fprintf(os.Stdout, "Error: %[1]s", err.Error())
        os.Exit(1)
    }
    os.Exit(0)
}

type ExOpOptions struct {
    configFlags genericclioptions.ConfigFlags
}

func NewExOpOptions(streams genericclioptions.IOStreams) *ExOpOptions {
    return &ExOpOptions{}
}

func newCmdEx(streams genericclioptions.IOStreams) *cobra.Command {
    o := NewExOpOptions(streams)

    cmd := &cobra.Command{
        RunE: func(c *cobra.Command, args []string) error {
            return o.Run()
        },
    }

    o.configFlags.AddFlags(cmd.Flags())

    return cmd
}

func (o *ExOpOptions) Run() error {
    return os.Setenv("THEBESTOFTIMES", "Sure it was.")
}

Example build and test script:

GO111MODULE="on" go build cmd/ex-com.go && \
   echo "First Print:" && \
   echo "$THEBESTOFTIMES" && \
   ./ex-com && \
   echo "Second Print:" && \
   echo "$THEBESTOFTIMES"

I would expect the output to look like this (since the environment variable is being set on line 48 of the go code):

go: finding k8s.io/cli-runtime/pkg/genericclioptions latest
go: finding k8s.io/cli-runtime/pkg latest
go: finding k8s.io/cli-runtime latest
First Print:

Second Print:
Sure it was.

But currently it looks like this:

go: finding k8s.io/cli-runtime/pkg/genericclioptions latest
go: finding k8s.io/cli-runtime/pkg latest
go: finding k8s.io/cli-runtime latest
First Print:

Second Print:

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 2024-五一综合模拟赛
    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭