当前位置:网站首页>Golang — 命令行工具cobra
Golang — 命令行工具cobra
2022-07-03 13:11:00 【风起云边】
Cobra

Cobra是一个用于Go语言的CLI框架。它包含一个用于创建强大的现代CLI应用程序的库,以及一个用于快速生成基于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
- 自动识别帮助 flag -h,–help
- 自动生成应用程序在 bash 下命令自动完成功能
- 自动生成应用程序的 man 手册
- 命令行别名
- 自定义 help 和 usage 信息
- 可选的与 viper apps 的紧密集成
概念
Cobra是建立在命令、参数和标志的结构上的。
Commands代表动作,Args是东西,Flags是这些动作的修饰符。
最好的应用读起来像句子。用户会知道如何使用应用程序,因为他们天生就知道如何使用它。
例如:
hugo server --port=1313
Command
Command是应用程序的中心点。应用程序支持的每个交互都包含在Command中。命令可以有子命令,也可以有选择地运行操作。
Flag
flag 是修改命令行为的一种方式。Cobra完全支持兼容posix标志以及Go标志包。Cobra命令可以定义贯穿子命令的标志,以及只对该命令可用的标志。
上面例子中--port即是一个flag
全局标识(Persistent Flags)
全局标识(Persistent Flags)会作用于其指定的命令与指定命令所有的子命令。
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
局部标识(Local Flags)
局部标示(Local Flags)仅作用于其指定命令。
rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
Run Hooks
可以在命令的主run函数之前或之后运行函数。PersistentPreRun和PreRun函数将在Run之前执行。persistentpoststrun和poststrun会在Run之后执行。如果子类不声明自己的Persistent*Run函数,它们将被子类继承。这些函数按以下顺序运行:
- PersistentPreRun
- PreRun
- Run
- PostRun
- PersistentPostRun
示例:
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "root [sub]",
Short: "My root command",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
},
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
},
}
var subCmd = &cobra.Command{
Use: "sub [no options!]",
Short: "My subcommand",
PreRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd Run with args: %v\n", args)
},
PostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
},
}
rootCmd.AddCommand(subCmd)
rootCmd.SetArgs([]string{
""})
rootCmd.Execute()
fmt.Println()
rootCmd.SetArgs([]string{
"sub", "arg1", "arg2"})
rootCmd.Execute()
}
output:
Inside rootCmd PersistentPreRun with args: []
Inside rootCmd PreRun with args: []
Inside rootCmd Run with args: []
Inside rootCmd PostRun with args: []
Inside rootCmd PersistentPostRun with args: []
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
Inside subCmd PreRun with args: [arg1 arg2]
Inside subCmd Run with args: [arg1 arg2]
Inside subCmd PostRun with args: [arg1 arg2]
Inside subCmd PersistentPostRun with args: [arg1 arg2]
边栏推荐
- Red hat satellite 6: better management of servers and clouds
- Logseq 评测:优点、缺点、评价、学习教程
- (first) the most complete way to become God of Flink SQL in history (full text 180000 words, 138 cases, 42 pictures)
- 已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)
- MySQL
- PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
- MapReduce实现矩阵乘法–实现代码
- SwiftUI 开发经验之作为一名程序员需要掌握的五个最有力的原则
- Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
- 今日睡眠质量记录77分
猜你喜欢

Introduction to the implementation principle of rxjs observable filter operator
![[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay](/img/18/b06e2e5a2f76dc2da1c2374b8424b3.png)
[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay

【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】

已解决(机器学习中查看数据信息报错)AttributeError: target_names

Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication

Mysql database basic operation - regular expression

SQL Injection (GET/Select)

mysql更新时条件为一查询

Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)

Universal dividend source code, supports the dividend of any B on the BSC
随机推荐
Unity render streaming communicates with unity through JS
Brief analysis of tensorboard visual processing cases
R语言使用data函数获取当前R环境可用的示例数据集:获取datasets包中的所有示例数据集、获取所有包的数据集、获取特定包的数据集
今日睡眠质量记录77分
Flink SQL knows why (16): dlink, a powerful tool for developing enterprises with Flink SQL
显卡缺货终于到头了:4000多块可得3070Ti,比原价便宜2000块拿下3090Ti
Asp. Net core1.1 without project JSON, so as to generate cross platform packages
常见的几种最优化方法Matlab原理和深度分析
Logseq 评测:优点、缺点、评价、学习教程
json序列化时案例总结
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
掌握Cypress命令行选项,是真正掌握Cypress的基础
AI scores 81 in high scores. Netizens: AI model can't avoid "internal examination"!
Introduction to the implementation principle of rxjs observable filter operator
使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
File uploading and email sending
人身变声器的原理
Spark practice 1: build spark operation environment in single node local mode
Oracle memory management
IBEM mathematical formula detection data set