Golang Argparse无法正确选择多个标志的值。

huangapple go评论129阅读模式
英文:

Golang Argparse not picking correct value for multiple flags

问题

我有一个名为test的golang二进制文件。我使用golang的argparse库定义了两个标志-p和-s。我希望用户按照以下场景传递它们:

./test -p
./test -s serviceName
./test -p -s serviceName

这意味着-p应该传递一个空值,而-s应该传递任何服务名称。第1和第2种情况都可以正常工作,但在第3种情况下,-p标志接收到了"-s"的值。我希望第3种情况中,-p的值为空(""),而-s的值为"serviceName"。

代码:

parser := argparse.NewParser("./test", "Check status/version of test")
parser.DisableHelp()
platformFormatVal := parser.String("p", "platform", &argparse.Options{Required: false, Help: "Print status of platform", Default: "Inplatform"})
serviceFormatVal := parser.String("s", "service", &argparse.Options{Required: false, Help: "Print status of service", Default: "Inservice"})
err := parser.Parse(os.Args)
if err != nil {
	//处理通用错误
}
platformFormat = *platformFormatVal
serviceFormat = *serviceFormatVal
英文:

I have a golang binary named test. I have two flags -p and -s using golang argparse library. I want user to pass them like below scenarios:

./test -p
./test -s serviceName
./test -p -s serviceName

Means -p should be passed with empty value and -s should be passed with any service name. 1 and 2 are working fine but in third -p flag is taking value "-s". What i want from 3rd is -p should be empty value ("") and -s should be "serviceName".
Code:

parser := argparse.NewParser("./test", "Check status/version of test")
parser.DisableHelp()
platformFormatVal := parser.String("p", "platform", &argparse.Options{Required: false, Help: "Print status of platform", Default: "Inplatform"})
serviceFormatVal := parser.String("s", "service", &argparse.Options{Required: false, Help: "Print status of service", Default: "Inservice"})
err := parser.Parse(os.Args)
if err != nil {
		//generic error
	}
platformFormat = *platformFormatVal
serviceFormat = *serviceFormatVal

答案1

得分: 1

你好!以下是翻译好的内容:

还没有使用过argparse库,只用了标准的flag库,但根据文档,你将p配置为字符串参数,而实际上它是一个布尔标志。

你应该像这样配置你的参数:

sArg := parser.String("s", ...)
pArg := parser.Flag("p", ...)

然后你可以这样使用它:

if *pArg {
   ...
}

希望对你有帮助!如果还有其他问题,请随时提问。

英文:

Haven't used argparse lib, only the standard flag, but according to the docs, you are configuring p as a string argument, while it is actually a boolean flag.

You should configure your arguments similar to this:

	sArg := parser.String("s", ...)
	pArg := parser.Flag("p", ...)

Then you can use it like this:

  if *pArg {
     ...
  }

huangapple
  • 本文由 发表于 2022年9月8日 18:06:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/73647321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定