标准库中的flag包用于解析命令行参数:
var (
flgHelp bool
flgEcho string
)
func parseCmdLineFlags() {
flag.BoolVar(&flgHelp, "help", false, "if true, show help")
flag.StringVar(&flgEcho, "echo", "", "")
flag.Parse()
}
func main() {
parseCmdLineFlags()
if flgHelp {
flag.Usage()
os.Exit(0)
}
fmt.Printf("flag -echo: '%s'\n", flgEcho)
remainingArgs := flag.Args()
for _, arg := range remainingArgs {
fmt.Printf("Remainig arg: '%s'\n", arg)
}
}
flag -echo: 'echo-arg'
Remainig arg: 'additional'
Remainig arg: 'arg'
上面的输出是调用go run $ file -echo echo-arg Additional arg的结果。
定义参数
假设你的程序有一个-retries整数选项。
你可以使用以下标志包注册此类选项:
var flgRetries int
defaultRetries := 0
usage := "retries specifies number of times to retry the operation"
flag.IntVar(&flgRetries, "retries", defaultRetries, usage)
还有其他常见类型的功能:
- flag.BoolVar
- flag.DurationVar
- flag.Float64Var
- flag.IntVar, flag.UIntVar, flag.Int64Var, flag.UInt64Var
- flag.StringVar
If you register int argument with name retries, the way to provide it on cmd-line is -retries {value}.
POSIX variant --retries or Windows variant /retries are not recognized.
For boolean values you can say: -help (implicitly true), -help=true or -help=false.
-help false is not a valid form for boolean variables.
Parsing and accessing remaining arguments
After parsing arguments, call flag.Parse().
Parsing fails if:
unknown flag was given on command-line
a flag didn’t parse based on its type (e.g. it was registered as int but the value was not a valid number)
In case of failure, help text describing flags is shown and program exits with error code 2.
You can explicitly print help text using flag.Usage(). This is often triggered by -help flag.
Help text is based on usage text provided in flag.IntVar and others.
Command-line arguments that don’t start with - are untouched and can be accessed with flag.Args().
局限性
flag包缺少的功能:
no support for POSIX style --name, only -name is supported
no support for short alternatives e.g. -n being synonym with --name
no suport for Windows style /name
If you need those features, your options are:
access raw cmd-line arguments
use a third party library
Access raw command line arguments
If flag package or a third-party library doesn’t provide the features you want, you can parse the arguments yourself.
func main() {
fmt.Printf("Name of executable: '%s'\n", os.Args[0])
args := os.Args[1:]
for i, arg := range args {
fmt.Printf("Arg %d, value: '%s'\n", i, arg)
}
}
Name of executable: '/tmp/go-build870077205/b001/exe/main'
Arg 0, value: '-echo'
Arg 1, value: 'echo-arg'
Arg 2, value: 'additional'
Arg 3, value: 'arg'
The above output is a result of go run $file -echo echo-arg additional arg.
Raw arguments
Raw command-line arguments can be accessed via []string slice os.Args.
First element is name of the executable.
Remaining elements are cmd-line arguments as decoded by OS shell.
On Windows cmd-line arguments are a single UTF-16 Unicode string.
Go runtime converts them to UTF-8 string and splits into separate arguments to unify handling across different operating systems.
Libraries for advanced parsing of command-line arguments
Functionaly provided by standard library package flag is limited.
其他提供了命令行参数解析的库:
- argparse - Command line argument parser inspired by Python’s argparse module.
- cli - Feature-rich and easy to use command-line package based on golang struct tags.
- cli - Simple and complete API for building command line interfaces in Go.
- cli-init - The easy way to start building Golang command line applications.
- climax - Alternative CLI with “human face”, in spirit of Go command.
- cobra - Commander for modern Go CLI interactions.
- commandeer - Dev-friendly CLI apps: sets up flags, defaults, and usage based on struct fields and tags.
- docopt.go - Command-line arguments parser that will make you smile.
- flag - Simple but powerful command line option parsing library for Go supporting subcommand.
- go-arg - Struct-based argument parsing in Go.
- go-flags - go command line option parser.
- gocmd - Go library for building command line applications.
- kingpin - Command line and flag parser supporting sub commands.
- mitchellh/cli - Go library for implementing command-line interfaces.
- mow.cli - Go library for building CLI applications with sophisticated flag and argument parsing and validation.
- pflag - Drop-in replacement for Go’s flag package, implementing POSIX/GNU-style –flags.
- sflags - Struct based flags generator for flag, urfave/cli, pflag, cobra, kingpin and other libraries.
- strumt - Library to create prompt chain.
- ukautz/clif - Small command line interface framework.
- urfave/cli - Simple, fast, and fun package for building command line apps in Go (formerly codegangsta/cli).