189 8069 5689

go语言命令行参数 go 命令行

27.Go 解析命令行参数

标准库中的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.

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

Go执行命令行操作

go中提供了 os/exec 包使用 Command 函数可以完成一些调用命令行的操作。因为系统的不同,调用的参数会有点些不一样。

其他的创建执行都是一样的。

我们可以封装一个函数,输入需要执行的命令,输入返回结果

调用测试

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

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

使用方式:

flag.Type(name, defValue, usage)

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

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

将flag绑定到一个变量上。


标题名称:go语言命令行参数 go 命令行
本文地址:http://cdxtjz.cn/article/hippgs.html

其他资讯