将cobra下载到 $GOPATH,用命令:

  1. go get -v github.com/spf13/cobra/cobra

然后使用 go install github.com/spf13/cobra/cobra, 安装后在 $GOBIN 下出现了cobra 可执行程序。如果你没有配置 $GOBIN,那么可以在$GOPATH/bin 下找到 cobra的可执行软件。

cobra程序只能在GOPATH之下使用,所以首先你需要进入到GOPATH的src目录之下,在该目录下,输入:

  1. cobra init demo

在你的当前目录下,应该已经生成了一个demo文件夹:

  1. demo
  2. ├── cmd
  3. └── root.go
  4. ├── LICENSE
  5. └── main.go

上述便是该文件夹的结构,我们可以进去该文件夹,运行:

  1. go run main.go

应该会打印如下结果:

  1. A longer description that spans multiple lines and likely contains examples and usage of using your application. For example:
  2. Cobra is a CLI library for Go that empowers applications.
  3. This application is a tool to generate the needed files
  4. to quickly create a Cobra application.

至此,我们的cobra项目便已经生成完毕。

如果你并不想运行cobra的可执行命令生成示例代码,只想在项目使用其库代码,则上面的内容可以忽略。

附 demo 文件夹的内容:

cmd/root.go:

  1. // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14.  
  15. package cmd
  16.  
  17. import (
  18. "fmt"
  19. "os"
  20.  
  21. homedir "github.com/mitchellh/go-homedir"
  22. "github.com/spf13/cobra"
  23. "github.com/spf13/viper"
  24. )
  25.  
  26. var cfgFile string
  27.  
  28. // rootCmd represents the base command when called without any subcommands
  29. var rootCmd = &cobra.Command{
  30. Use: "demo",
  31. Short: "A brief description of your application",
  32. Long: `A longer description that spans multiple lines and likely contains
  33. examples and usage of using your application. For example:
  34.  
  35. Cobra is a CLI library for Go that empowers applications.
  36. This application is a tool to generate the needed files
  37. to quickly create a Cobra application.`,
  38. // Uncomment the following line if your bare application
  39. // has an action associated with it:
  40. // Run: func(cmd *cobra.Command, args []string) { },
  41. }
  42.  
  43. // Execute adds all child commands to the root command and sets flags appropriately.
  44. // This is called by main.main(). It only needs to happen once to the rootCmd.
  45. func Execute() {
  46. if err := rootCmd.Execute(); err != nil {
  47. fmt.Println(err)
  48. os.Exit()
  49. }
  50. }
  51.  
  52. func init() {
  53. cobra.OnInitialize(initConfig)
  54.  
  55. // Here you will define your flags and configuration settings.
  56. // Cobra supports persistent flags, which, if defined here,
  57. // will be global for your application.
  58. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
  59.  
  60. // Cobra also supports local flags, which will only run
  61. // when this action is called directly.
  62. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  63. }
  64.  
  65. // initConfig reads in config file and ENV variables if set.
  66. func initConfig() {
  67. if cfgFile != "" {
  68. // Use config file from the flag.
  69. viper.SetConfigFile(cfgFile)
  70. } else {
  71. // Find home directory.
  72. home, err := homedir.Dir()
  73. if err != nil {
  74. fmt.Println(err)
  75. os.Exit()
  76. }
  77.  
  78. // Search config in home directory with name ".demo" (without extension).
  79. viper.AddConfigPath(home)
  80. viper.SetConfigName(".demo")
  81. }
  82.  
  83. viper.AutomaticEnv() // read in environment variables that match
  84.  
  85. // If a config file is found, read it in.
  86. if err := viper.ReadInConfig(); err == nil {
  87. fmt.Println("Using config file:", viper.ConfigFileUsed())
  88. }
  89. }

main.go:

  1. // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14.  
  15. package main
  16.  
  17. import "demo/cmd"
  18.  
  19. func main() {
  20. cmd.Execute()
  21. }

添加子命令

实际操作其实cobra都能帮你完成,假设我们现在需要添加一个test参数,在项目文件夹下命令行输入:

  1. cobra add test

执行完成后,现在我们的demo结构应该是:

  1. .
  2. ├── cmd
  3. ├── root.go
  4. └── test.go
  5. ├── LICENSE
  6. └── main.go

可以看到,在cmd目录下,已经生成了一个与我们命令同名的go文件,你也许已经猜测到,与该命令有关的操作也正是在此处实现。现在执行这个子命令:

  1. go run main.go test

命令行将会打印输出test called
那么现在又有一个问题,如果我们想添加子命令下的子命令呢?
现在让我们打开test.go,你应该看到如下的文件内容:

  1. // Copyright © 2017 NAME HERE <EMAIL ADDRESS>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14.  
  15. package cmd
  16.  
  17. import (
  18. "fmt"
  19.  
  20. "github.com/spf13/cobra"
  21. )
  22.  
  23. // testCmd represents the test command
  24. var testCmd = &cobra.Command{
  25. Use: "test",
  26. Short: "A brief description of your command",
  27. Long: `A longer description that spans multiple lines and likely contains examples
  28. and usage of using your command. For example:
  29.  
  30. Cobra is a CLI library for Go that empowers applications.
  31. This application is a tool to generate the needed files
  32. to quickly create a Cobra application.`,
  33. Run: func(cmd *cobra.Command, args []string) {
  34. fmt.Println("test called")
  35. },
  36. }
  37.  
  38. func init() {
  39. rootCmd.AddCommand(testCmd)
  40.  
  41. // Here you will define your flags and configuration settings.
  42.  
  43. // Cobra supports Persistent Flags which will work for this command
  44. // and all subcommands, e.g.:
  45. // testCmd.PersistentFlags().String("foo", "", "A help for foo")
  46.  
  47. // Cobra supports local flags which will only run when this command
  48. // is called directly, e.g.:
  49. // testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  50. }

你会发现,在init中有一句 rootCmd.AddCommand(testCmd) 这个rootCmd是什么?打开root.go,你会发现rootCmd其实就是我们的根命令。我相信机智的同学已经猜出来我们添加子命令的子命令的方法了。现在让我们在cmd目录下新建testson.go文件,项目文件结构为:

  1. .
  2. ├── cmd
  3. ├── root.go
  4. └── test.go
  5. └── testson.go
  6. ├── LICENSE
  7. └── main.go

把test.go的内容复制进去,并testson.go文件修改为如下内容:

cmd/testson.go:

  1. // Copyright © 2017 NAME HERE <EMAIL ADDRESS>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14.  
  15. package cmd
  16.  
  17. import (
  18. "fmt"
  19.  
  20. "github.com/spf13/cobra"
  21. )
  22.  
  23. // testCmd represents the test command
  24. var testsonCmd = &cobra.Command{
  25. Use: "testson",
  26. Short: "A brief description of your command",
  27. Long: `A longer description that spans multiple lines and likely contains examples
  28. and usage of using your command. For example:
  29.  
  30. Cobra is a CLI library for Go that empowers applications.
  31. This application is a tool to generate the needed files
  32. to quickly create a Cobra application.`,
  33. Run: func(cmd *cobra.Command, args []string) {
  34. fmt.Println("testson called")
  35. },
  36. }
  37.  
  38. func init() {
  39. testCmd.AddCommand(testsonCmd)
  40.  
  41. // Here you will define your flags and configuration settings.
  42.  
  43. // Cobra supports Persistent Flags which will work for this command
  44. // and all subcommands, e.g.:
  45. // testCmd.PersistentFlags().String("foo", "", "A help for foo")
  46.  
  47. // Cobra supports local flags which will only run when this command
  48. // is called directly, e.g.:
  49. // testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  50. }

现在在命令行运行:

  1. go run main.go test testson

当你看到testson called,恭喜你,子命令添加成功!否则你应当检查你的代码是否有误。

添加参数

我相信从init函数中的注释中,你已经得到了足够多的信息来自己操作添加flag,但我还是想要啰嗦两句。首先是persistent参数,当你的参数作为persistent flag存在时,如注释所言,在其所有的子命令之下该参数都是可见的。而local flag则只能在该命令调用时执行。可以做一个简单的测试,在test.go的init函数中,添加如下内容:

  1. testCmd.PersistentFlags().String("foo", "", "A help for foo")
  2. testCmd.Flags().String("foolocal", "", "A help for foo")

现在在命令行 go run main.go test -h 得到如下结果:

  1. $ go run main.go test -h
  2. A longer description that spans multiple lines and likely contains examples
  3. and usage of using your command. For example:
  4.  
  5. Cobra is a CLI library for Go that empowers applications.
  6. This application is a tool to generate the needed files
  7. to quickly create a Cobra application.
  8.  
  9. Usage:
  10. demo test [flags]
  11. demo test [command]
  12.  
  13. Available Commands:
  14. testson A brief description of your command
  15.  
  16. Flags:
  17. --foo string A help for foo
  18. --foolocal string A help for foo
  19. -h, --help help for test
  20.  
  21. Global Flags:
  22. --config string config file (default is $HOME/.demo.yaml)
  23.  
  24. Use "demo test [command] --help" for more information about a command.

接着让我们再运行 go run main.go test testson -h

  1. $ go run main.go test testson -h
  2. A longer description that spans multiple lines and likely contains examples
  3. and usage of using your command. For example:
  4.  
  5. Cobra is a CLI library for Go that empowers applications.
  6. This application is a tool to generate the needed files
  7. to quickly create a Cobra application.
  8.  
  9. Usage:
  10. demo test testson [flags]
  11.  
  12. Flags:
  13. -h, --help help for testson
  14.  
  15. Global Flags:
  16. --config string config file (default is $HOME/.demo.yaml)
  17. --foo string A help for foo

可以发现在Gloabal Flags的变化。test作为root的子命令,仍然可以使用root的persistent flag-> config(可以查看root.go),而testson作为test的子命令,不仅可以使用test的persistent flag-> fool, 也可以使用test父命令的persistent flag。从而我们可以直观的看出persistent的作用范围是该命令之后的所有子命令。接下来你可能会问,那flag支持什么类型参数?答案是,请查看官方文档
请注意,cmd.Flags().String()与 cmd.Flags().StringP()是不一样的。假如我们在test.go的init下增加如下两行:

  1. testCmd.Flags().String("f", "", "test")
  2. testCmd.Flags().StringP("aaa", "a", "", "test")

前者调用需要如下形式:

  1. go run main.go test --f

后者有如下两种形式调用:

  1. go run main.go test --aaa
  2. go run main.go test -a

另外可以额外告知你如何使用slice作为参数,如[]string:

  1. testCmd.Flags().StringSliceP("arr","r", nil, "test arr")

调用该参数的方法为:

  1. go run main.go test -r "a,b,c"

请不要键入多余空格(除非确实需要键入),也不要使用空格替代逗号作为分割符。

获取参数值

在知道了如何设置参数后,我们的下一步当然便是需要在运行时获取该参数的值。现在让我们把注意力放到test.go的此部分:

  1. var testCmd = &cobra.Command{
  2. Use: "test",
  3. Short: "A brief description of your command",
  4. Long: `A longer description that spans multiple lines and likely contains examples
  5. and usage of using your command. For example:
  6.  
  7. Cobra is a CLI library for Go that empowers applications.
  8. This application is a tool to generate the needed files
  9. to quickly create a Cobra application.`,
  10. Run: func(cmd *cobra.Command, args []string) {
  11. fmt.Println("test called")
  12. },
  13. }

让我们把注意力重新放到上面的代码上。我们也很容易可以猜测到Use,Short,Long三个参数的作用,这里便不做阐述(你可以参照添加子命令的子命令的部分的输出)。显而易见,我们应该在Run这里来获取参数并执行我们的命令功能。获取参数其实也并不复杂。以testCmd.Flags().StringP("aaa", "a", "", "test")此为例,我们可以在Run函数里添加:

  1. str := testCmd.Flags().GetString("aaa")

这样便可以获取到该参数的值了,其余类型参数获取也是同理。如 testCmd.Flags().GetStringSlice("arr"),规律并不难见。

Golang: Cobra命令行参数库的使用的更多相关文章

  1. 微软官方的.net命令行参数库

    虽然现在是图形化大行其道的时代,但让程序支持命令行启动对于专业的领域还是有不少需求的..net本身并没有内置对命令行解析的支持,我之前就写过一篇文章让.Net程序支持命令行启动介绍了几个第三方的命令行 ...

  2. Golang: 打印命令行参数

    记得最早在学校机房学习 Java 时,照着书上的例子,写一个最简单 main 方法,当程序运行并在屏幕上打印出 hello world 时,内心竟有种莫名的激动,相信很多人都有这种经历吧. 不管学什么 ...

  3. 浅谈optparse 解析命令行参数库

    使用的背景 在工作中我们经常要制定运行脚本的一些参数,因为有些东西是随着我么需求要改变的,所以在为们写程序的时候就一定不能把写死,这样我们就要设置参数 在python中我们可以通过sys 模板的arg ...

  4. linux 中解析命令行参数(getopt_long用法)

    linux 中解析命令行参数(getopt_long用法) http://www.educity.cn/linux/518242.html 详细解析命令行的getopt_long()函数 http:/ ...

  5. GO语言标准库—命令行参数解析FLAG

    flag包是Go语言标准库提供用来解析命令行参数的包,使得开发命令行工具更为简单 常用方法 1.flag.Usage 输出使用方法,如linux下ls -h的帮助输出 2.flag.Type(参数名, ...

  6. Google开源命令行参数解析库gflags

    Google开源命令行参数解析库gflags http://blog.csdn.net/lming_08/article/details/25072899 CMDLINE的解析 http://blog ...

  7. boost之program_options库,解析命令行参数、读取配置文件

    一.命令行解析 tprogram_options解析命令行参数示例代码: #include <iostream> using namespace std; #include <boo ...

  8. TensorFlow-谷歌深度学习库 命令行参数

    程序的入口: tf.app.run tf.app.run( main=None, argv=None ) 运行程序,可以提供'main'函数以及函数参数列表.处理flag解析然后执行main函数. 什 ...

  9. golang命令行参数

    os.Args获取命令行参数 os.Args是一个srting的切片,用来存储所有的命令行参数 package main import ( "fmt" "os" ...

随机推荐

  1. 【dfs判负环】BZOJ1489: [HNOI2009]最小圈

    Description 找出一个平均边权最小的圈. Solution 经典问题,二分答案判断有无负环. 但数据范围大,普通spfa会超时,于是用dfs判负环(快多了). 思路是dis设为0,枚举每个点 ...

  2. [Usaco2005 dec]Layout 排队布局 差分约束

    填坑- 差分约束一般是搞一个不等式组,求xn-x1的最大最小值什么的,求最大值就转化成xa<=xb+w这样的,然后建图跑最短路(这才是最终约束的),举个例子 x1<=x0+2x2<= ...

  3. Linux下全局安装composer

    下载composer curl -sS https://getcomposer.org/installer | php 将composer.phar文件移动到bin目录以便全局使用composer命令 ...

  4. golang 中 string 转换 []byte 的一道笔试题

    背景 去面试的时候遇到一道和 string 相关的题目,记录一下用到的知识点.题目如下: s:="123" ps:=&s b:=[]byte(s) pb:=&b s ...

  5. vue2.0 axios封装、vuex介绍

    一.前言 博主也是vue道路上的行者,道行不深,希望自己的东西能对大家有所帮助.这篇博客针对 了解过vue基础,但是没有做过vue项目的童鞋.如果想看基础指令,可以看我之前的一篇博客,请点击  跳转, ...

  6. TensorFlow之RNN:堆叠RNN、LSTM、GRU及双向LSTM

    RNN(Recurrent Neural Networks,循环神经网络)是一种具有短期记忆能力的神经网络模型,可以处理任意长度的序列,在自然语言处理中的应用非常广泛,比如机器翻译.文本生成.问答系统 ...

  7. vue中引入babel步骤

    vue中引入babel步骤 vue项目中普遍使用es6语法,但有时我们的项目需要兼容低版本浏览器,这时就需要引入babel插件,将es6转成es5. 1.安装babel-polyfill插件 npm ...

  8. zookeeper源码 — 二、集群启动—leader选举

    上一篇介绍了zookeeper的单机启动,集群模式下启动和单机启动有相似的地方,但是也有各自的特点.集群模式的配置方式和单机模式也是不一样的,这一篇主要包含以下内容: 概念介绍:角色,服务器状态 服务 ...

  9. PostgreSQL(PostGIS)安装和入门的若干问题

    1. 装完PostgreSQL后记得打开pgAdmin4启动一下服务器和启动一下数据库,否则PostGIS装不上. 2. pgAdmin4是网页,而3是客户端,当然都可以在File - Prefere ...

  10. Android开发利器之stetho

    文章同步自javaexception Stetho是什么? github上地址https://github.com/facebook/stetho stetho是facebook出品的一款开发调试工具 ...