英文:
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 {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论