golang flag 解析入參

首先一個例子:post

package main
import (
    "fmt"
    "flag"
)

func main(){

    data_path := flag.String("D","/home/manu/sample/","DB data path")
    log_file := flag.String("l","/home/manu/sample.log","log file")
    nowait_flag :=flag.Bool("W",false,"do not wait until operation completes")

    flag.Parse()

    var cmd string = flag.Arg(0);

    fmt.Printf("action   : %s\n",cmd)
    fmt.Printf("data path: %s\n",*data_path)
    fmt.Printf("log file : %s\n",*log_file)
    fmt.Printf("nowait     : %v\n",*nowait_flag)

    fmt.Printf("-------------------------------------------------------\n")

    fmt.Printf("there are %d non-flag input param\n",flag.NArg())
    for i,param := range flag.Args(){
        fmt.Printf("#%d    :%s\n",i,param)
    }


}

 OK,咱們分析下代碼(分割線下面的咱們暫時不看):code

    第一行對應的是data_path的解析規則字符串

    -D選項對應的值是字符串類型字符串,input

    默認值是「/home/manu/sample」,cmd

    DB data path提示信息或者help信息或者說明是。string

manu@manu-hacks:~/code/go/self$ go run pg_ctl_parse.go  -D /home/manu/DB_data/ -l /home/manu/DB_data/postgres_manu.log -W start
action   : start
data path: /home/manu/DB_data/
log file : /home/manu/DB_data/postgres_manu.log
nowait	: true
-------------------------------------------------------
there are 1 non-flag input param
#0	:start

manu@manu-hacks:~/code/go/self$ go run pg_ctl_parse.go   -l=/home/manu/DB_data/postgres_manu.log -W -D /home/manu/DB_data/  start
action   : start
data path: /home/manu/DB_data/
log file : /home/manu/DB_data/postgres_manu.log
nowait	: true
-------------------------------------------------------
there are 1 non-flag input param
#0	:start

    咱們看到了,解析出了data_path,log_file不管 -l -D出現的順序如何,只要正常的出現了,就能正常的解析。it

    可是晴朗的天空中也有一片烏雲,start不是這種 -key=alue 或則-option的類型,flag是解析不了的。咱們稱這種參數爲non-flag參數,flag解析遇到non-flag參數就中止了:io

s := f.args[0]
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
    return false, nil
}

  因此若是咱們將non-flag參數放在最前面,flag什麼也不會解析,由於flag遇到了這個就中止解析了。class

manu@manu-hacks:~/code/go/self$ go run pg_ctl_parse.go  start -l=/home/manu/DB_data/postgres_manu.log -W -D /home/manu/DB_data/  
action   : start
data path: /home/manu/sample
log file : /home/manu/sample.log
nowait   : false
-------------------------------------------------------
there are 5 non-flag input param
#0	:start
#1	:-l=/home/manu/DB_data/postgres_manu.log
#2	:-W
#3	:-D
#4	:/home/manu/DB_data/

  OK,flag提供了Arg(i),Args()來獲取non-flag參數,NArg()來獲取non-flag的個數。正如咱們們sample 代碼看到的。import

fmt.Printf("there are %d non-flag input param\n",flag.NArg())
    for i,param := range flag.Args(){
        fmt.Printf("#%d :%s\n",i,param)
    }

    flag還提供了NFlag()獲取那些匹配上的參數的個數。

    從例子上看,flag package頗有用,可是並無強大到解析一切的程度。

    若是你有相似-option或者-key =value這種參數,不妨試試 flag。若是你的入參解析很是複雜,flag可能捉襟見肘。

相關文章
相關標籤/搜索