设为首页收藏本站
网站公告 | 这是第一条公告
     

 找回密码
 立即注册
缓存时间11 现在时间11 缓存数据 她接到喜欢了七年的他的电话。他对她说:我们在一起吧。尽管听到电话那头别人的窃窃笑声。她还昰淡定地说:好啊。然后她问:大冒险又输了吧?他说:我选的是真心话。

她接到喜欢了七年的他的电话。他对她说:我们在一起吧。尽管听到电话那头别人的窃窃笑声。她还昰淡定地说:好啊。然后她问:大冒险又输了吧?他说:我选的是真心话。 -- 过火

查看: 727|回复: 1

golang中命令行库cobra的使用方法示例

[复制链接]

  离线 

TA的专栏

  • 打卡等级:无名新人
  • 打卡总天数:2
  • 打卡月天数:0
  • 打卡总奖励:22
  • 最近打卡:2025-01-08 08:46:36
等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
25
主题
21
精华
0
金钱
97
积分
50
注册时间
2023-7-30
最后登录
2025-5-23

发表于 2024-6-28 04:35:09 来自手机 | 显示全部楼层 |阅读模式
简介

Cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序。下面是Cobra使用的一个演示:

1.jpg

Cobra提供的功能

      
  • 简易的子命令行模式,如 app server, app fetch等等  
  • 完全兼容posix命令行模式  
  • 嵌套子命令subcommand  
  • 支持全局,局部,串联flags  
  • 使用Cobra很容易的生成应用程序和命令,使用cobra create appname和cobra add cmdname  
  • 如果命令输入错误,将提供智能建议,如 app srver,将提示srver没有,是否是app server  
  • 自动生成commands和flags的帮助信息  
  • 自动生成详细的help信息,如app help  
  • 自动识别-h,--help帮助flag  
  • 自动生成应用程序在bash下命令自动完成功能  
  • 自动生成应用程序的man手册  
  • 命令行别名  
  • 自定义help和usage信息  
  • 可选的紧密集成的viper apps
如何使用

上面所有列出的功能我没有一一去使用,下面我来简单介绍一下如何使用Cobra,基本能够满足一般命令行程序的需求,如果需要更多功能,可以研究一下源码github。
安装cobra

Cobra是非常容易使用的,使用go get来安装最新版本的库。当然这个库还是相对比较大的,可能需要安装它可能需要相当长的时间,这取决于你的速网。安装完成后,打开GOPATH目录,bin目录下应该有已经编译好的cobra.exe程序,当然你也可以使用源代码自己生成一个最新的cobra程序。
  1. > go get -v github.com/spf13/cobra/cobra
复制代码
使用cobra生成应用程序

假设现在我们要开发一个基于CLIs的命令程序,名字为demo。首先打开CMD,切换到GOPATH的src目录下[^1],执行如下指令:
[^1]:cobra.exe只能在GOPATH目录下执行
  1. src> ..\bin\cobra.exe init demo
  2. Your Cobra application is ready at
  3. C:\Users\liubo5\Desktop\transcoding_tool\src\demo
  4. Give it a try by going there and running `go run main.go`
  5. Add commands to it by running `cobra add [cmdname]`
复制代码
在src目录下会生成一个demo的文件夹,如下:
  1. ▾ demo
  2.     ▾ cmd/
  3.         root.go
  4.     main.go
复制代码
如果你的demo程序没有subcommands,那么cobra生成应用程序的操作就结束了。
如何实现没有子命令的CLIs程序
接下来就是可以继续demo的功能设计了。例如我在demo下面新建一个包,名称为imp。如下:
  1. ▾ demo
  2.     ▾ cmd/
  3.         root.go
  4.     ▾ imp/
  5.         imp.go
  6.         imp_test.go
  7.     main.go
复制代码
imp.go文件的代码如下:
  1. package imp

  2. import(
  3. "fmt"
  4. )

  5. func Show(name string, age int) {
  6. fmt.Printf("My Name is %s, My age is %d\n", name, age)
  7. }
复制代码
demo程序成命令行接收两个参数name和age,然后打印出来。打开cobra自动生成的main.go文件查看:
  1. // Copyright © 2016 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. package main

  15. import "demo/cmd"

  16. func main() {
  17. cmd.Execute()
  18. }
复制代码
可以看出main函数执行cmd包,所以我们只需要在cmd包内调用imp包就能实现demo程序的需求。接着打开root.go文件查看:
  1. // Copyright © 2016 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. package cmd

  15. import (
  16. "fmt"
  17. "os"

  18. "github.com/spf13/cobra"
  19. "github.com/spf13/viper"
  20. )

  21. var cfgFile string

  22. // RootCmd represents the base command when called without any subcommands
  23. var RootCmd = &cobra.Command{
  24. Use: "demo",
  25. Short: "A brief description of your application",
  26. Long: `A longer description that spans multiple lines and likely contains
  27. examples and usage of using your application. For example:

  28. Cobra is a CLI library for Go that empowers applications.
  29. This application is a tool to generate the needed files
  30. to quickly create a Cobra application.`,
  31. // Uncomment the following line if your bare application
  32. // has an action associated with it:
  33. // Run: func(cmd *cobra.Command, args []string) { },
  34. }

  35. // Execute adds all child commands to the root command sets flags appropriately.
  36. // This is called by main.main(). It only needs to happen once to the rootCmd.
  37. func Execute() {
  38. if err := RootCmd.Execute(); err != nil {
  39.   fmt.Println(err)
  40.   os.Exit(-1)
  41. }
  42. }

  43. func init() {
  44. cobra.OnInitialize(initConfig)

  45. // Here you will define your flags and configuration settings.
  46. // Cobra supports Persistent Flags, which, if defined here,
  47. // will be global for your application.

  48. RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
  49. // Cobra also supports local flags, which will only run
  50. // when this action is called directly.
  51. RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  52. }

  53. // initConfig reads in config file and ENV variables if set.
  54. func initConfig() {
  55. if cfgFile != "" { // enable ability to specify config file via flag
  56.   viper.SetConfigFile(cfgFile)
  57. }

  58. viper.SetConfigName(".demo") // name of config file (without extension)
  59. viper.AddConfigPath("$HOME") // adding home directory as first search path
  60. viper.AutomaticEnv()   // read in environment variables that match

  61. // If a config file is found, read it in.
  62. if err := viper.ReadInConfig(); err == nil {
  63.   fmt.Println("Using config file:", viper.ConfigFileUsed())
  64. }
  65. }
复制代码
从源代码来看cmd包进行了一些初始化操作并提供了Execute接口。十分简单,其中viper是cobra集成的配置文件读取的库,这里不需要使用,我们可以注释掉(不注释可能生成的应用程序很大约10M,这里没哟用到最好是注释掉)。cobra的所有命令都是通过cobra.Command这个结构体实现的。为了实现demo功能,显然我们需要修改RootCmd。修改后的代码如下:
  1. // Copyright © 2016 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. package cmd

  15. import (
  16. "fmt"
  17. "os"

  18. "github.com/spf13/cobra"
  19. // "github.com/spf13/viper"
  20. "demo/imp"
  21. )

  22. //var cfgFile string
  23. var name string
  24. var age int

  25. // RootCmd represents the base command when called without any subcommands
  26. var RootCmd = &cobra.Command{
  27. Use: "demo",
  28. Short: "A test demo",
  29. Long: `Demo is a test appcation for print things`,
  30. // Uncomment the following line if your bare application
  31. // has an action associated with it:
  32. Run: func(cmd *cobra.Command, args []string) {
  33.   if len(name) == 0 {
  34.    cmd.Help()
  35.    return
  36.   }
  37.   imp.Show(name, age)
  38. },
  39. }

  40. // Execute adds all child commands to the root command sets flags appropriately.
  41. // This is called by main.main(). It only needs to happen once to the rootCmd.
  42. func Execute() {
  43. if err := RootCmd.Execute(); err != nil {
  44.   fmt.Println(err)
  45.   os.Exit(-1)
  46. }
  47. }

  48. func init() {
  49. // cobra.OnInitialize(initConfig)

  50. // Here you will define your flags and configuration settings.
  51. // Cobra supports Persistent Flags, which, if defined here,
  52. // will be global for your application.

  53. // RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
  54. // Cobra also supports local flags, which will only run
  55. // when this action is called directly.
  56. // RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  57. RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
  58. RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
  59. }

  60. // initConfig reads in config file and ENV variables if set.
  61. //func initConfig() {
  62. // if cfgFile != "" { // enable ability to specify config file via flag
  63. //  viper.SetConfigFile(cfgFile)
  64. // }

  65. // viper.SetConfigName(".demo") // name of config file (without extension)
  66. // viper.AddConfigPath("$HOME") // adding home directory as first search path
  67. // viper.AutomaticEnv()   // read in environment variables that match

  68. // // If a config file is found, read it in.
  69. // if err := viper.ReadInConfig(); err == nil {
  70. //  fmt.Println("Using config file:", viper.ConfigFileUsed())
  71. // }
  72. //}
复制代码
到此demo的功能已经实现了,我们编译运行一下看看实际效果:
  1. >demo.exe
  2. Demo is a test appcation for print things
  3. Usage:
  4.   demo [flags]
  5. Flags:
  6.   -a, --age int       person's age
  7.   -h, --help          help for demo
  8.   -n, --name string   person's name
复制代码
  1. >demo -n borey --age 26
  2. My Name is borey, My age is 26
复制代码
如何实现带有子命令的CLIs程序
在执行cobra.exe init demo之后,继续使用cobra为demo添加子命令test:
  1. src\demo>..\..\bin\cobra add test
  2. test created at C:\Users\liubo5\Desktop\transcoding_tool\src\demo\cmd\test.go
复制代码
在src目录下demo的文件夹下生成了一个cmd\test.go文件,如下:
  1. ▾ demo
  2.     ▾ cmd/
  3.         root.go
  4.         test.go
  5.     main.go
复制代码
接下来的操作就和上面修改root.go文件一样去配置test子命令。效果如下:
  1. src\demo>demo
  2. Demo is a test appcation for print things

  3. Usage:
  4. demo [flags]
  5. demo [command]

  6. Available Commands:
  7. test  A brief description of your command

  8. Flags:
  9. -a, --age int  person's age
  10. -h, --help   help for demo
  11. -n, --name string person's name

  12. Use "demo [command] --help" for more information about a command.
复制代码
可以看出demo既支持直接使用标记flag,又能使用子命令
  1. src\demo>demo test -h
  2. A longer description that spans multiple lines and likely contains examples
  3. and usage of using your command. For example:

  4. Cobra is a CLI library for Go that empowers applications.
  5. This application is a tool to generate the needed files
  6. to quickly create a Cobra application.

  7. Usage:
  8. demo test [flags]
复制代码
调用test命令输出信息,这里没有对默认信息进行修改。
  1. src\demo>demo tst
  2. Error: unknown command "tst" for "demo"

  3. Did you mean this?
  4.   test

  5. Run 'demo --help' for usage.
  6. unknown command "tst" for "demo"

  7. Did you mean this?
  8.   test
复制代码
这是错误命令提示功能
OVER

Cobra的使用就介绍到这里,更新细节可去github详细研究一下。这里只是一个简单的使用入门介绍,如果有错误之处,敬请指出,谢谢~
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对晓枫资讯的支持。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
晓枫资讯-科技资讯社区-免责声明
免责声明:以上内容为本网站转自其它媒体,相关信息仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同其观点或证实其内容的真实性。
      1、注册用户在本社区发表、转载的任何作品仅代表其个人观点,不代表本社区认同其观点。
      2、管理员及版主有权在不事先通知或不经作者准许的情况下删除其在本社区所发表的文章。
      3、本社区的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,举报反馈:点击这里给我发消息进行删除处理。
      4、本社区一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
      5、以上声明内容的最终解释权归《晓枫资讯-科技资讯社区》所有。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

  离线 

TA的专栏

等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
0
主题
0
精华
0
金钱
17
积分
14
注册时间
2022-12-24
最后登录
2022-12-24

发表于 2025-4-8 00:30:40 | 显示全部楼层
感谢楼主,顶。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~
严禁发布广告,淫秽、色情、赌博、暴力、凶杀、恐怖、间谍及其他违反国家法律法规的内容。!晓枫资讯-社区
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1楼
2楼

手机版|晓枫资讯--科技资讯社区 本站已运行

CopyRight © 2022-2025 晓枫资讯--科技资讯社区 ( BBS.yzwlo.com ) . All Rights Reserved .

晓枫资讯--科技资讯社区

本站内容由用户自主分享和转载自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。

如有侵权、违反国家法律政策行为,请联系我们,我们会第一时间及时清除和处理! 举报反馈邮箱:点击这里给我发消息

Powered by Discuz! X3.5

快速回复 返回顶部 返回列表