在普通模式下,设置环境变量似乎很简单。 os
库具有一个Setenv
函数,该函数可以完成任务。我在眼镜蛇命令中执行该操作时遇到麻烦。是我缺少一种简单的方法,还是目前不支持此功能?
我想做的事的例子:
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.")
}
示例构建和测试脚本:
GO111MODULE="on" go build cmd/ex-com.go && \
echo "First Print:" && \
echo "$THEBESTOFTIMES" && \
./ex-com && \
echo "Second Print:" && \
echo "$THEBESTOFTIMES"
我希望输出看起来像这样(由于在go代码的第48行设置了环境变量):
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.
但是目前看起来像这样:
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: