简介

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

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程序。

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

使用cobra生成应用程序

假设现在我们要开发一个基于CLIs的命令程序,名字为demo。首先打开CMD,切换到GOPATH的src目录下[^1],执行如下指令:

[^1]:cobra.exe只能在GOPATH目录下执行

src> ..\bin\cobra.exe init demo

Your Cobra application is ready at

C:\Users\liubo5\Desktop\transcoding_tool\src\demo

Give it a try by going there and running `go run main.go`

Add commands to it by running `cobra add [cmdname]`

在src目录下会生成一个demo的文件夹,如下:

▾ demo

▾ cmd/

root.go

main.go

如果你的demo程序没有subcommands,那么cobra生成应用程序的操作就结束了。

如何实现没有子命令的CLIs程序

接下来就是可以继续demo的功能设计了。例如我在demo下面新建一个包,名称为imp。如下:

▾ demo

▾ cmd/

root.go

▾ imp/

imp.go

imp_test.go

main.go

imp.go文件的代码如下:

package imp

import(

"fmt"

)

func Show(name string, age int) {

fmt.Printf("My Name is %s, My age is %d\n", name, age)

}

demo程序成命令行接收两个参数name和age,然后打印出来。打开cobra自动生成的main.go文件查看:

// Copyright © 2016 NAME HERE

//

// Licensed under the Apache License, Version 2.0 (the "License");

// you may not use this file except in compliance with the License.

// You may obtain a copy of the License at

//

// http://www.apache.org/licenses/LICENSE-2.0

//

// Unless required by applicable law or agreed to in writing, software

// distributed under the License is distributed on an "AS IS" BASIS,

// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

// See the License for the specific language governing permissions and

// limitations under the License.

package main

import "demo/cmd"

func main() {

cmd.Execute()

}

可以看出main函数执行cmd包,所以我们只需要在cmd包内调用imp包就能实现demo程序的需求。接着打开root.go文件查看:

// Copyright © 2016 NAME HERE

//

// Licensed under the Apache License, Version 2.0 (the "License");

// you may not use this file except in compliance with the License.

// You may obtain a copy of the License at

//

// http://www.apache.org/licenses/LICENSE-2.0

//

// Unless required by applicable law or agreed to in writing, software

// distributed under the License is distributed on an "AS IS" BASIS,

// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

// See the License for the specific language governing permissions and

// limitations under the License.

package cmd

import (

"fmt"

"os"

"github.com/spf13/cobra"

"github.com/spf13/viper"

)

var cfgFile string

// RootCmd represents the base command when called without any subcommands

var RootCmd = &cobra.Command{

Use: "demo",

Short: "A brief description of your application",

Long: `A longer description that spans multiple lines and likely contains

examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.

This application is a tool to generate the needed files

to quickly create a Cobra application.`,

// Uncomment the following line if your bare application

// has an action associated with it:

// Run: func(cmd *cobra.Command, args []string) { },

}

// Execute adds all child commands to the root command sets flags appropriately.

// This is called by main.main(). It only needs to happen once to the rootCmd.

func Execute() {

if err := RootCmd.Execute(); err != nil {

fmt.Println(err)

os.Exit(-1)

}

}

func init() {

cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags, which, if defined here,

// will be global for your application.

RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")

// Cobra also supports local flags, which will only run

// when this action is called directly.

RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}

// initConfig reads in config file and ENV variables if set.

func initConfig() {

if cfgFile != "" { // enable ability to specify config file via flag

viper.SetConfigFile(cfgFile)

}

viper.SetConfigName(".demo") // name of config file (without extension)

viper.AddConfigPath("$HOME") // adding home directory as first search path

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.

if err := viper.ReadInConfig(); err == nil {

fmt.Println("Using config file:", viper.ConfigFileUsed())

}

}

从源代码来看cmd包进行了一些初始化操作并提供了Execute接口。十分简单,其中viper是cobra集成的配置文件读取的库,这里不需要使用,我们可以注释掉(不注释可能生成的应用程序很大约10M,这里没哟用到最好是注释掉)。cobra的所有命令都是通过cobra.Command这个结构体实现的。为了实现demo功能,显然我们需要修改RootCmd。修改后的代码如下:

// Copyright © 2016 NAME HERE

//

// Licensed under the Apache License, Version 2.0 (the "License");

// you may not use this file except in compliance with the License.

// You may obtain a copy of the License at

//

// http://www.apache.org/licenses/LICENSE-2.0

//

// Unless required by applicable law or agreed to in writing, software

// distributed under the License is distributed on an "AS IS" BASIS,

// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

// See the License for the specific language governing permissions and

// limitations under the License.

package cmd

import (

"fmt"

"os"

"github.com/spf13/cobra"

// "github.com/spf13/viper"

"demo/imp"

)

//var cfgFile string

var name string

var age int

// RootCmd represents the base command when called without any subcommands

var RootCmd = &cobra.Command{

Use: "demo",

Short: "A test demo",

Long: `Demo is a test appcation for print things`,

// Uncomment the following line if your bare application

// has an action associated with it:

Run: func(cmd *cobra.Command, args []string) {

if len(name) == 0 {

cmd.Help()

return

}

imp.Show(name, age)

},

}

// Execute adds all child commands to the root command sets flags appropriately.

// This is called by main.main(). It only needs to happen once to the rootCmd.

func Execute() {

if err := RootCmd.Execute(); err != nil {

fmt.Println(err)

os.Exit(-1)

}

}

func init() {

// cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags, which, if defined here,

// will be global for your application.

// RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")

// Cobra also supports local flags, which will only run

// when this action is called directly.

// RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

RootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")

RootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")

}

// initConfig reads in config file and ENV variables if set.

//func initConfig() {

// if cfgFile != "" { // enable ability to specify config file via flag

// viper.SetConfigFile(cfgFile)

// }

// viper.SetConfigName(".demo") // name of config file (without extension)

// viper.AddConfigPath("$HOME") // adding home directory as first search path

// viper.AutomaticEnv() // read in environment variables that match

// // If a config file is found, read it in.

// if err := viper.ReadInConfig(); err == nil {

// fmt.Println("Using config file:", viper.ConfigFileUsed())

// }

//}

到此demo的功能已经实现了,我们编译运行一下看看实际效果:

>demo.exe

Demo is a test appcation for print things

Usage:

demo [flags]

Flags:

-a, --age int       person's age

-h, --help          help for demo

-n, --name string   person's name>demo -n borey --age 26

My Name is borey, My age is 26

如何实现带有子命令的CLIs程序

在执行cobra.exe init demo之后,继续使用cobra为demo添加子命令test:

src\demo>..\..\bin\cobra add test

test created at C:\Users\liubo5\Desktop\transcoding_tool\src\demo\cmd\test.go

在src目录下demo的文件夹下生成了一个cmd\test.go文件,如下:

▾ demo

▾ cmd/

root.go

test.go

main.go

接下来的操作就和上面修改root.go文件一样去配置test子命令。效果如下:

src\demo>demo

Demo is a test appcation for print things

Usage:

demo [flags]

demo [command]

Available Commands:

test A brief description of your command

Flags:

-a, --age int person's age

-h, --help help for demo

-n, --name string person's name

Use "demo [command] --help" for more information about a command.

可以看出demo既支持直接使用标记flag,又能使用子命令

src\demo>demo test -h

A longer description that spans multiple lines and likely contains examples

and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.

This application is a tool to generate the needed files

to quickly create a Cobra application.

Usage:

demo test [flags]

调用test命令输出信息,这里没有对默认信息进行修改。

src\demo>demo tst

Error: unknown command "tst" for "demo"

Did you mean this?

test

Run 'demo --help' for usage.

unknown command "tst" for "demo"

Did you mean this?

test

这是错误命令提示功能

OVER

Cobra的使用就介绍到这里,更新细节可去github详细研究一下。这里只是一个简单的使用入门介绍,如果有错误之处,敬请指出,谢谢~

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

cobra mysql_golang中命令行库cobra的使用方法示例相关推荐

  1. Go命令行库Cobra的使用

    点击上方"朱小厮的博客",选择"设为星标" 回复"1024"获取独家整理的学习资料 欢迎跳转到本文的原文链接:https://honeypp ...

  2. go命令行库-cobra

    Cobra介绍 Cobra 是一个用于创建强大的现代 CLI 应用程序的库.几乎包含了你所需要的所有元素. Cobra 用于许多 Go 项目,例如Kubernetes.Docker.GitHub CL ...

  3. python读音有道词典-利用python实现命令行有道词典的方法示例

    前言 由于一直用Linux系统,对于词典的支持特别不好,对于我这英语渣渣的人来说,当看英文文档就一直卡壳,之前用惯了有道词典,感觉很不错,虽然有网页版的但是对于全站英文的网页来说并不支持.索性自己实现 ...

  4. python有道字典_利用python实现命令行有道词典的方法示例

    前言 由于一直用Linux系统,对于词典的支持特别不好,对于我这英语渣渣的人来说,当看英文文档就一直卡壳,之前用惯了有道词典,感觉很不错,虽然有网页版的但是对于全站英文的网页来说并不支持.索性自己实现 ...

  5. Go 通过 cobra 快速构建命令行应用

    这里填写标题 1. Go 通过 cobra 快速构建命令行应用 1.1. cobra 能帮我们做啥? 1.2. cobra 基础使用 1.3. 概念 1.4. Commands 1.5. Flags ...

  6. Python 命令行库的大乱

    当你想实现一个命令行程序时,或许第一个想到的是用 Python 来实现.比如 CentOS 上大名鼎鼎的包管理工具 yum 就是基于 Python 实现的. 而 Python 的世界中有很多命令行库, ...

  7. Google 开源的 Python 命令行库:fire 实现 git 命令

    一.前言 在前面三篇介绍 fire 的文章中,我们全面了解了 fire 强大而不失简洁的能力.按照惯例,我们要像使用 argparse.docopt 和 click 一样使用 fire 来实现 git ...

  8. 文本编辑器中命令行参数的应用

    文章目录 1 文本编辑器中命令行参数的应用 1 文本编辑器中命令行参数的应用 我们要知道对于每一个应用程序我们都能够接收命令行参数,那么对于GUI系统中命令行参数如何传递到应用程序呢? 主要有如下两种 ...

  9. Java中命令行调用大坑

    Java中命令行调用大坑 背景 我司有一个查询服务接口机,QPS大概40~50,调用方式是Java调用Shell命令行的方式,核心代码如下: Process ps = Runtime.getRunti ...

最新文章

  1. 云技术与云计算的区别
  2. 公办低分二本_山东的5所专科院校,属于本省公办,适合低分学生报考
  3. python spearman相关系数_Python spearman相关系数不匹配 .
  4. Weex Ui - Weex Conf 2018 干货分享
  5. eclipse的tomcat如何运行自动弹网页_4个国外网页设计网站案例欣赏
  6. 广义动量定理之速度V的应用分析
  7. go and git 代理
  8. Android的面孔_Actiyity
  9. 抗衰老,吃这些食物越来越年轻
  10. oracle获取用户名,Oracle 用户名详解
  11. Android 10正式版发布,支持5G和折叠屏设备
  12. MiPony– 杀手级免费网盘下载工具 可挂机下载支持YunFile
  13. android6.0连接WIFI后显示“已连接,但无法访问互联网”实际可以上网
  14. 【已解决】格式化SD卡提示“这张磁盘有写保护”,试过将SD开关拨向两边,均失败。
  15. 移动端 click 300ms 延迟,如何解决
  16. kasp技术原理_SNP检测Massarray法怎么样?中高通量大样本适用吗?
  17. verilog使用1bit全加器实现4bit全加器【行波进位法】
  18. java程序设计特点_Java编程语言的特点
  19. 学习Python是为了什么
  20. (小)算法题(长期更新)

热门文章

  1. 【运营学习】项目运营经理所具备的能力
  2. Qt | UDP广播通信的使用、实战项目使用案例
  3. 有没有柯尼卡打印机的过滤器
  4. Exploration (HDU - 5222)
  5. Google云端硬盘Colab 指定文件夹
  6. 祭奠小米帝国属臆想,顺利上市不成问题!
  7. php 根据url生成图片并保存
  8. C语言代码优化的实用方法大总结
  9. java wsl连接tuxedo_Tuxedo 通讯方式解析(二)
  10. Python递归实现猴子吃桃问题