如何在Go语言中使用flag包对命令行进行参数解析

如何在Go语言中使用flag包对命令行进行参数解析,第1张

flag 是Go 标准库提供的解析命令行参数的包。

使用方式:

flag.Type(name, defValue, usage)

其中Type为String, Int, Bool等;并返回一个相应类型的指针。

flag.TypeVar(&flagvar, name, defValue, usage)

将flag绑定到一个变量上。

标准库中的flag包用于解析命令行参数:

上面的输出是调用go run $ file -echo echo-arg Additional arg的结果。

定义参数

假设你的程序有一个-retries整数选项

你可以使用以下标志包注册此类选项:

还有其他常见类型的功能:

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

If flag package or a third-party library doesn’t provide the features you want, you can parse the arguments yourself.

The above output is a result of go run $file -echo echo-arg additional arg.

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.

Functionaly provided by standard library package flag is limited.

其他提供了命令行参数解析的库:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11778025.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存