dousong2967 2018-04-23 11:37
浏览 21

如何从命令对象传递参数

I use the following code which need to pass value from functions root, value

var cfBuild = &cobra.Command{
    Use:   "build",
    Short: "Build",
    Run: func(cmd *cobra.Command, args []string) {


        root, value := Build(target)
    },
    PersistentPostRun: func(cmd *cobra.Command, args []string) {
   //Here I need to use root, value
   } 
}

I can do it by using global variable but is there a nice way to avoid global in this case ?

This is the repo, I didnt find any nice way to do it ... https://github.com/spf13/cobra

Btw there is option to use viper

like ...

Run: func(cmd *cobra.Command, args []string) {
    root, value := Build(target)
    viper.Set("root", root)
    viper.Set("value", value)

and then get it in the other method... Is it good direction?

  • 写回答

1条回答 默认 最新

  • duanpa5237 2018-07-23 14:21
    关注

    you don't need Viper for that. Just create 2 singletons (variables with global scope in the command file) and you can assign them to your Build function returns.

    Example

    package cmd
    
    var (
        root,
        value string
    )
    
    var cfBuild = &cobra.Command{
        Use:   "build",
        Short: "Build",
        Run: func(cmd *cobra.Command, args []string) {
            root, value = Build(target)
        },
        PersistentPostRun: func(cmd *cobra.Command, args []string) {
            fmt.Printf("%s, %s", root, value)
       } 
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?