go parsing command line parameter flag package

content

1. Get command line parameters

Second, the basic use of the flag package

1. Flag parameter type

2. Define the command line flag parameter

3, flag other functions

4. Complete example of flag package


The flag package built into the Go language implements the parsing of command line parameters, and the flag package makes it easier to develop command line tools.

1. Get command line parameters

os.Args: If you simply want to get command line arguments, you can use os.Args to get command line arguments as in the code example below.

package main

import (
    "fmt"
    "os"
)

//os.Args demo
func main() {
    //os.Args是一个[]string
    if len(os.Args) > 0 {
        for index, arg := range os.Args {
            fmt.Printf("args[%d]=%v\n", index, arg)
        }
    }
}

After compiling the above code with go build -o "args_demo", execute:

$ ./args_demo a b c d
args[0]=./args_demo
args[1]=a
args[2]=b
args[3]=c
args[4]=d

os.Args is a string slice that stores command line arguments, and its first element is the name of the executable.

Second, the basic use of the flag package

import flag

1. Flag parameter type

The command line parameter types supported by the flag package are bool, int, int64, uint, uint64, float float64, string, duration.

flag parameter

valid value

string flag

legal string

Integer flag

1234, 0664, 0x1234 and other types, can also be negative.

float flag

legal floating point number

bool type flag

1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False。

time period flag

Any valid time period string. Such as "300ms", "-1.5h", "2h45m".

Legal units are "ns", "us" / "µs", "ms", "s", "m", "h".

2. Define the command line flag parameter

There are two common ways to define command-line flag parameters.

flag.Type()

The basic format is as follows:

flag.Type(flag名, 默认值, 帮助信息)*Type

For example, if we want to define three command line parameters of name, age, and marriage, we can define it as follows:

name := flag.String("name", "张三", "姓名")
age := flag.Int("age", 18, "年龄")
married := flag.Bool("married", false, "婚否")
delay := flag.Duration("d", 0, "时间间隔")

It should be noted that at this time, name, age, married, and delay are all pointers of the corresponding type.

flag.TypeVar()

The basic format is as follows: flag.TypeVar(Type pointer, flag name, default value, help information) For example, if we want to define three command line parameters of name, age, and marriage, we can define it as follows:

var name string
var age int
var married bool
var delay time.Duration

flag.StringVar(&name, "name", "张三", "姓名")
flag.IntVar(&age, "age", 18, "年龄")
flag.BoolVar(&married, "married", false, "婚否")
flag.DurationVar(&delay, "d", 0, "时间间隔")

The variable obtained by flag.TypeVar(), not a pointer, can be used directly

Remarks: The above command line parameters can be obtained through flag.Type() and flag.TypeVar(). After obtaining, you must use flag.Parse() to parse

flag.Parse()

After the command line flag parameters are defined by the above two methods, the command line parameters need to be parsed by calling flag.Parse().

The supported command line parameter formats are as follows:

-flag xxx (使用空格,一个-符号)
--flag xxx (使用空格,两个-符号)
-flag=xxx (使用等号,一个-符号)
--flag=xxx (使用等号,两个-符号)

Among them, the parameters of boolean type must be specified using the equal sign.

Flag parsing stops before the first non-flag argument (a single "-" is not a flag argument), or after the terminator "-".

3, flag other functions

flag.Args() 返回命令行参数后的其他参数,以[]string类型
flag.NArg() //返回命令行参数后的其他参数个数
flag.NFlag() //返回使用的命令行参数个数

4. Complete example of flag package

func main() {
    //定义命令行参数方式1
    var name string
    var age int
    var married bool
    var delay time.Duration
    
    flag.StringVar(&name, "name", "张三", "姓名")
    flag.IntVar(&age, "age", 18, "年龄")
    flag.BoolVar(&married, "married", false, "婚否")
    flag.DurationVar(&delay, "d", 0, "延迟的时间间隔")

    //解析命令行参数
    flag.Parse()
    fmt.Println(name, age, married, delay)
   
     //返回命令行参数后的其他参数,这是个数组
    fmt.Println(flag.Args())
    
    //返回使用的命令行参数个数
    fmt.Println(flag.NFlag())
    
    //返回命令行参数后的其他参数个数
    fmt.Println(flag.NArg())
}

Command line usage:

1) Tips for using command line parameters:

$ ./flag_demo -help
Usage of ./flag_demo:
  -age int
        年龄 (default 18)
  -d duration
        时间间隔
  -married
        婚否
  -name string
        姓名 (default "张三")

2) Use the command line flag parameter normally:

$ ./flag_demo -name pprof --age 28 -married=false -d=1h30m
pprof 28 false 1h30m0s
[]
0
4

3) Use non-flag command line arguments:

$ ./flag_demo a b c
张三 18 false 0s
[a b c]
3
0

Guess you like

Origin blog.csdn.net/demored/article/details/124295528