当前位置:网站首页>Go parsing command line parameter flag package
Go parsing command line parameter flag package
2022-04-22 04:46:00 【Qin Tian】
Catalog
One 、 Get command line parameters
Two 、flag Basic use of package
2、 Define the command line flag Parameters
4、flag Package complete example
Go Language built in flag The package implements the parsing of command line parameters ,flag Packages make developing command-line tools easier .
One 、 Get command line parameters
os.Args: If you simply want to get command line arguments , It can be used like the following code example os.Args To get command line arguments .
package main
import (
"fmt"
"os"
)
//os.Args demo
func main() {
//os.Args It's a []string
if len(os.Args) > 0 {
for index, arg := range os.Args {
fmt.Printf("args[%d]=%v\n", index, arg)
}
}
}
Execute the above code go build -o "args_demo" After the compilation , perform :
$ ./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 parameters , Its first element is the name of the execution file .
Two 、flag Basic use of package
import flag
1、flag Parameter type
flag The command line parameter types supported by the package are bool、int、int64、uint、uint64、float float64、string、duration.
| flag Parameters |
Valid values |
| character string flag |
Legal string |
| Integers flag |
1234、0664、0x1234 Other types , It can also be negative . |
| Floating point numbers flag |
Legal floating point number |
| bool type flag |
1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False. |
| Period of time flag |
Any legal time period string . Such as ”300ms”、”-1.5h”、”2h45m”. Legal units include ”ns”、”us” /“µs”、”ms”、”s”、”m”、”h”. |
2、 Define the command line flag Parameters
There are two common definitions of the command line flag Parameter method .
flag.Type()
The basic format is as follows :
flag.Type(flag name , The default value is , Help information )*Type
For example, we want to define names 、 Age 、 There are three command line parameters for marriage , We can define... As follows :
name := flag.String("name", " Zhang San ", " full name ")
age := flag.Int("age", 18, " Age ")
married := flag.Bool("married", false, " marriage ")
delay := flag.Duration("d", 0, " The time interval ")
It should be noted that , here name、age、married、delay Are pointers to corresponding types .
flag.TypeVar()
The basic format is as follows : flag.TypeVar(Type The pointer , flag name , The default value is , Help information ) For example, we want to define names 、 Age 、 There are three command line parameters for marriage , We can define... As follows :
var name string
var age int
var married bool
var delay time.Duration
flag.StringVar(&name, "name", " Zhang San ", " full name ")
flag.IntVar(&age, "age", 18, " Age ")
flag.BoolVar(&married, "married", false, " marriage ")
flag.DurationVar(&delay, "d", 0, " The time interval ")
flag.TypeVar() Get the variable of , Not a pointer can be used directly
remarks : Approved above flag.Type(),flag.TypeVar() You can obtain command line parameters in both ways , Must be used after obtaining flag.Parse() analysis
flag.Parse()
Define the command line in two ways flag After the parameter , You need to call flag.Parse() To parse the command line parameters .
The supported command line parameter formats are as follows :
-flag xxx ( Use spaces , One - Symbol )
--flag xxx ( Use spaces , Two - Symbol )
-flag=xxx ( Use equal sign , One - Symbol )
--flag=xxx ( Use equal sign , Two - Symbol )
among , Parameters of boolean type must be specified with equal sign .
Flag Resolution in the first non flag Parameters ( Single ”-“ No flag Parameters ) Stop before , Or in the Terminator ”–“ Stop after .
3、flag Other functions
flag.Args() Return other parameters after command line parameters , With []string type
flag.NArg() // Returns the number of other parameters after the command line parameters
flag.NFlag() // Returns the number of command line arguments used
4、flag Package complete example
func main() {
// Define the command line arguments 1
var name string
var age int
var married bool
var delay time.Duration
flag.StringVar(&name, "name", " Zhang San ", " full name ")
flag.IntVar(&age, "age", 18, " Age ")
flag.BoolVar(&married, "married", false, " marriage ")
flag.DurationVar(&delay, "d", 0, " The interval of delay ")
// Parsing command line arguments
flag.Parse()
fmt.Println(name, age, married, delay)
// Return other parameters after command line parameters , This is an array
fmt.Println(flag.Args())
// Returns the number of command line arguments used
fmt.Println(flag.NFlag())
// Returns the number of other parameters after the command line parameters
fmt.Println(flag.NArg())
}
Command line usage :
1) Command line parameters use prompt :
$ ./flag_demo -help
Usage of ./flag_demo:
-age int
Age (default 18)
-d duration
The time interval
-married
marriage
-name string
full name (default " Zhang San ")
2) Use the command line normally flag Parameters :
$ ./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
Zhang San 18 false 0s
[a b c]
3
0
版权声明
本文为[Qin Tian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210805116408.html
边栏推荐
- [Chestnut Sugar GIS] SuperMap - How to make hyperlinks for Data
- Es next related
- 6_ Data analysis modeling
- 11.libevent对水平触发和边缘触发测试
- CommDGI: Community detection oriented deep graph infomax 2020 CIKM
- 创意几何点线面三角形孟菲斯海报banneer广告设计ai矢量背景素材
- 【板栗糖GIS】supermap—如何为数据制造超链接
- Climb the actor's name and add a link
- Matlab曲线的颜色、线型等参数设置方法
- 2021-08-14
猜你喜欢
![[chestnut sugar GIS] ArcMap - how to combine multiple images into one](/img/b4/fb1ceaf4cbb040ae0fc1d0ffbc46f9.png)
[chestnut sugar GIS] ArcMap - how to combine multiple images into one

C-随手写10

goland汉化解决方法(下载插件失败的情况下)
![[chestnut sugar GIS] ArcMap - how to make map combination table with buffer](/img/40/83db5ad08c787fc83919a19f334833.png)
[chestnut sugar GIS] ArcMap - how to make map combination table with buffer

2022T电梯修理考试练习题及在线模拟考试
![C language simple [stack and queue] (bracket matching problem)](/img/3d/092daf5d4896aabaf12d34497fe643.png)
C language simple [stack and queue] (bracket matching problem)
![[chestnut sugar GIS] SuperMap - how to create hyperlinks for data](/img/6d/8b46c96d3ec1005481919e5e81ce80.png)
[chestnut sugar GIS] SuperMap - how to create hyperlinks for data

博云 BeyondCMP 云管理平台 5.6 版本发布

rsync概述

2022g2 boiler operator certificate examination question bank and online simulation examination
随机推荐
14. Buffferevent timeout event processing
Article 1 of linked list
11. Libevent tests horizontal trigger and edge trigger
AT32 MCU F435/437 DFU DEMO
[stack and queue] simple application of C language ⌊ stack and queue realize each other, circular queue ⌉
Creative geometry point line surface triangle Memphis poster banner advertising design AI vector background material
Leetcode sword finger offer 17 Print from 1 to maximum n digits
Calculator (force buckle)
Setting method of parameters such as color and linetype of MATLAB curve
rpc error: code = Unavailable desc = error reading from server: EOF
安装opencv时遇到的报错
爬演员名字加链接
2022T电梯修理考试试题及在线模拟考试
LeetCode 剑指 Offer 18. 删除链表的节点
2022t elevator repair test questions and online simulation test
Paper reading (48): a library of optimization algorithms for organizational design
[untitled]
Mapbox creates multiple draggable marker points
13.bufferevent接受和发送数据
[untitled]