douyan1244 2016-08-02 21:41
浏览 351
已采纳

使用github.com/spf13/cobra获取参数值

I am using the github.com/spf13/cobra package to interpret process' command-line arguments, and I'm having difficulty understanding how parameter values are determined.

I have a working program (below) which uses internal variables that get updated with parameter values:

OptPort := 8088

rootCmd := &cobra.Command{
    Use:   "server",
    Short: "Root command short version",
    Long:  "Root command long version",
}

startCmd := &cobra.Command{
    Use:   "start",
    Short: "Start command short version",
    Long:  "Start command long version",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("args: " + strings.Join(args, " "))
        fmt.Println("port: " + OptPort)
    },
}
startCmd.Flags().IntVarP(&OptPort, "port", "p", OptPort, "Port to listen to")

rootCmd.AddCommand(startCmd)

rootCmd.Execute()

The output I get is as follows:

args:
port: 8088

I realize that I can get the port value by interrogating the port variable, but I would have thought the values would be in the args variable also. Is the args variable empty because I am doing something wrong? If the args variable is expected to be empty, what is the purpose of the args variable?

  • 写回答

1条回答 默认 最新

  • dqnrk44682 2016-08-04 15:48
    关注

    The args variable is for extra parameters that are passed into that particular cobra verb. For example, if you wanted your start verb on the server command to (for example) require a particular configuration file, you could simply pass that in like

    server start -p 8080 config.yml

    and "config.yml" is placed in args[0].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿