亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > Golang > 正文

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

2020-04-01 18:54:40
字體:
來源:轉載
供稿:網友

簡介

Cobra既是一個用來創建強大的現代CLI命令行的golang庫,也是一個生成程序應用和命令行文件的程序。下面是Cobra使用的一個演示:

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 atC:/Users/liubo5/Desktop/transcoding_tool/src/demoGive 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 impimport( "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 <EMAIL ADDRESS>//// 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 mainimport "demo/cmd"func main() { cmd.Execute()}

可以看出main函數執行cmd包,所以我們只需要在cmd包內調用imp包就能實現demo程序的需求。接著打開root.go文件查看:

// Copyright © 2016 NAME HERE <EMAIL ADDRESS>//// 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 cmdimport ( "fmt" "os" "github.com/spf13/cobra" "github.com/spf13/viper")var cfgFile string// RootCmd represents the base command when called without any subcommandsvar RootCmd = &cobra.Command{ Use: "demo", Short: "A brief description of your application", Long: `A longer description that spans multiple lines and likely containsexamples 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 filesto 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 <EMAIL ADDRESS>//// 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 cmdimport ( "fmt" "os" "github.com/spf13/cobra" // "github.com/spf13/viper" "demo/imp")//var cfgFile stringvar name stringvar age int// RootCmd represents the base command when called without any subcommandsvar 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 testtest 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>demoDemo is a test appcation for print thingsUsage: demo [flags] demo [command]Available Commands: test  A brief description of your commandFlags: -a, --age int  person's age -h, --help   help for demo -n, --name string person's nameUse "demo [command] --help" for more information about a command.

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

src/demo>demo test -hA longer description that spans multiple lines and likely contains examplesand 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 filesto quickly create a Cobra application.Usage: demo test [flags]

調用test命令輸出信息,這里沒有對默認信息進行修改。

src/demo>demo tstError: unknown command "tst" for "demo"Did you mean this?  testRun 'demo --help' for usage.unknown command "tst" for "demo"Did you mean this?  test

這是錯誤命令提示功能

OVER

Cobra的使用就介紹到這里,更新細節可去github詳細研究一下。這里只是一個簡單的使用入門介紹,如果有錯誤之處,敬請指出,謝謝~

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
国产午夜精品视频| 成人亚洲欧美一区二区三区| 日本久久久a级免费| 欧美在线性视频| 亚洲品质视频自拍网| 青青久久av北条麻妃黑人| 久久久久久久久久久免费| 菠萝蜜影院一区二区免费| 欧美激情视频一区二区三区不卡| 久久五月天色综合| 日韩精品在线私人| 日韩精品在线免费播放| 亚洲自拍偷拍一区| 亚洲国产97在线精品一区| 国产免费一区二区三区在线观看| 日韩在线免费观看视频| 91精品久久久久久久久久入口| 日韩精品视频在线观看网址| 国产精品视频专区| 亚洲精品免费一区二区三区| 国产精品视频区1| 国产+成+人+亚洲欧洲| 午夜精品国产精品大乳美女| 91sao在线观看国产| 亚洲精品久久久久久久久久久久久| 欧美一区二区三区艳史| 日韩极品精品视频免费观看| 4438全国成人免费| 日韩黄色高清视频| 欧美日韩亚洲网| 国产脚交av在线一区二区| 久久99亚洲精品| 欧美富婆性猛交| 日韩在线播放视频| 在线精品播放av| 91av在线看| 88国产精品欧美一区二区三区| 中文字幕欧美日韩| 成人午夜黄色影院| 亚洲国产成人久久综合一区| 97色在线观看免费视频| 日韩欧美在线中文字幕| 美女国内精品自产拍在线播放| 高清亚洲成在人网站天堂| 国产精品第100页| 亚洲三级免费看| 国产v综合v亚洲欧美久久| 日韩精品视频免费专区在线播放| 成人亚洲综合色就1024| 久久99国产精品自在自在app| 尤物九九久久国产精品的特点| 91影院在线免费观看视频| 国产精品成人一区二区三区吃奶| 欧美精品在线免费观看| 精品视频9999| 日韩成人在线网站| 久久免费在线观看| 欧美大片欧美激情性色a∨久久| 欧美成人在线免费视频| 欧美高清无遮挡| 97久久久久久| 国产精品91一区| 毛片精品免费在线观看| 亚洲跨种族黑人xxx| 欧美另类老女人| 国产一区视频在线播放| 久久精品一本久久99精品| 国产精品麻豆va在线播放| 91亚洲国产精品| 91麻豆国产语对白在线观看| 国内伊人久久久久久网站视频| 热久久美女精品天天吊色| 伦伦影院午夜日韩欧美限制| 国产亚洲精品久久久久久777| 美女黄色丝袜一区| 97精品国产aⅴ7777| 亚洲电影免费观看高清完整版| 国产精品久久久久久久久久尿| 国产精品高潮在线| 精品国产一区二区三区久久久| 91tv亚洲精品香蕉国产一区7ujn| 免费不卡欧美自拍视频| 毛片精品免费在线观看| 日韩大片免费观看视频播放| 国产亚洲日本欧美韩国| 国产国产精品人在线视| 国产一区二区激情| 亚洲精品久久久久久久久久久久久| 97在线免费观看| 日韩欧中文字幕| 777777777亚洲妇女| 国产精品国模在线| 亚洲精品99久久久久中文字幕| 精品高清一区二区三区| 日韩av第一页| 久久99精品久久久久久青青91| 日韩国产精品亚洲а∨天堂免| 亚洲韩国青草视频| 亚洲成人av中文字幕| 日韩欧美精品网址| 成人免费视频97| 亚洲精品欧美极品| 91精品国产91久久久久福利| 日本国产欧美一区二区三区| 午夜精品美女自拍福到在线| 亚洲精品久久久久久久久久久久| 亚洲电影成人av99爱色| 亚洲男人天堂久| 久久99精品视频一区97| 91产国在线观看动作片喷水| 欧美亚洲激情视频| 在线精品视频视频中文字幕| 欧美成人免费va影院高清| 日韩精品免费在线观看| 色婷婷亚洲mv天堂mv在影片| 国产在线精品成人一区二区三区| 日韩在线观看你懂的| 国产午夜精品美女视频明星a级| 国产成人一区二区三区| 日本成人精品在线| 欧美老女人性视频| 国产日韩欧美在线看| 上原亚衣av一区二区三区| 精品久久久香蕉免费精品视频| 国产美女精品免费电影| 自拍偷拍亚洲欧美| 91久久久久久久一区二区| 久久久亚洲欧洲日产国码aⅴ| 欧美精品videosex性欧美| 亚洲图片在线综合| 日韩免费看的电影电视剧大全| 日韩高清电影免费观看完整版| 欧美午夜无遮挡| 国产精品成人播放| 91精品视频在线播放| 国产极品jizzhd欧美| 日韩av免费看网站| 国产欧美日韩中文字幕在线| 8x海外华人永久免费日韩内陆视频| 久久久噜久噜久久综合| 日本精品一区二区三区在线播放视频| 这里只有精品在线播放| 久久综合国产精品台湾中文娱乐网| 欧美日韩中文在线观看| 日韩av电影免费观看高清| 91极品女神在线| 97视频国产在线| 欧美激情a∨在线视频播放| 中文字幕视频在线免费欧美日韩综合在线看| 成人日韩av在线| 91中文精品字幕在线视频| 国产精品免费在线免费| 日韩精品在线视频| 亚洲午夜未满十八勿入免费观看全集| 在线观看亚洲视频| 精品久久香蕉国产线看观看亚洲| 精品自拍视频在线观看| 日韩美女毛茸茸| 久久精品国产96久久久香蕉| 91精品国产高清久久久久久| 日韩a**中文字幕| 亚洲免费伊人电影在线观看av| 国产精品看片资源| 亚洲欧美www|