golang中的pflag示例

如今晚上在家啃kubeadm的源碼,html

在啃源碼前,pflag,viper,cobra這三件套好像是必須的,node

那就先弄懂一下這三個套件的套路吧。git

第一個,pflag.github

http://www.javashuo.com/article/p-fbaetuuy-mx.html函數

https://github.com/spf13/pflagui

pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.spa

pflag is compatible with the GNU extensions to the POSIX recommendations for command-line options. For a more precise description, see the "Command-line flag syntax" section below.命令行

pflag 包與 flag 包的工做原理甚至是代碼實現都是相似的,下面是 pflag 相對 flag 的一些優點:orm

  • 支持更加精細的參數類型:例如,flag 只支持 uint 和 uint64,而 pflag 額外支持 uint八、uint1六、int32 等類型。
  • 支持更多參數類型:ip、ip mask、ip net、count、以及全部類型的 slice 類型。
  • 兼容標準 flag 庫的 Flag 和 FlagSet:pflag 更像是對 flag 的擴展。
  • 原生支持更豐富的功能:支持 shorthand、deprecated、hidden 等高級功能。

 

package main

import flag "github.com/spf13/pflag"

import (
	"fmt"
	"strings"
)

// 定義命令行參數對應的變量
var cliName = flag.StringP("name", "n", "nick", "Input Your Name")
var cliAge = flag.IntP("age", "a", 22, "Input Your Age")
var cliGender = flag.StringP("gender", "g", "male", "Input Your Gender")
var cliOK = flag.BoolP("ok", "o", false, "Input Are You OK?")
var cliDes = flag.StringP("des-detail", "d", "", "Input Description")
var cliOldFlag = flag.StringP("badflag", "b", "just for test", "Input badflag")

func wordSepNomalizeFunc(f *flag.FlagSet, name string) flag.NormalizedName {
	from := []string{"-", "_"}
	to := "."
	for _, sep := range from {
		name = strings.Replace(name, sep, to, -1)
	}
	return flag.NormalizedName(name)
}

func main() {
	// 設置標準化參數名稱的函數
	flag.CommandLine.SetNormalizeFunc(wordSepNomalizeFunc)
	
	// 爲 age 參數設置 NoOptDefVal
	flag.Lookup("age").NoOptDefVal = "25"
	
	// 把 badflag 參數標記爲即將廢棄的,請用戶使用 des-detail 參數
	flag.CommandLine.MarkDeprecated("badflag", "please use --des-detail instead")
	// 把 badflag 參數的 shorthand 標記爲即將廢棄的,請用戶使用 des-detail 的 shorthand 參數
	flag.CommandLine.MarkShorthandDeprecated("badflag", "please use -d instead")
	
	// 在幫助文檔中隱藏參數 gender
	flag.CommandLine.MarkHidden("gender")
	
	// 把用戶傳遞的命令行參數解析爲對應變量的值
	flag.Parse()
	
	fmt.Println("name=", *cliName)
	fmt.Println("age=", *cliAge)
	fmt.Println("gender=", *cliGender)
	fmt.Println("ok=", *cliOK)
	fmt.Println("des=", *cliDes)
}

  

輸出的樣子:htm

 

最後,混用flag及pflag時,注意使用的方法

import (
	goflag "flag"
	flag "github.com/spf13/pflag"
)

var ip *int = flag.Int("flagname", 1234, "help message for flagname")

func main() {
	flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
	flag.Parse()
}
相關文章
相關標籤/搜索