英文:
Golang flag package stops parsing when encountering a non-flag
问题
内置的flags包在遇到进程的第一个非标志参数时似乎会中断解析。考虑以下应用程序:
package main
import (
"flag"
"fmt"
)
func main() {
alpha := flag.String("alpha", "", "the first")
beta := flag.String("beta", "", "the second")
flag.Parse()
fmt.Println("ALPHA: " + *alpha)
fmt.Println("BETA: " + *beta)
}
在提供了一个“子命令”的三个不同调用的输出如下所示:
$ ./app --alpha 1 --beta 2 hi
ALPHA: 1
BETA: 2
$ ./app --alpha 1 hi --beta 2
ALPHA: 1
BETA:
$ ./app hi --alpha 1 --beta 2
ALPHA:
BETA:
如何使用flags包来重新创建类似于git status --short的子命令后跟标志的功能呢?
英文:
The built-in flags package seems to break parsing upon encountering the first non-flag argument for a process. Consider this application:
package main
import (
"flag"
"fmt"
)
func main() {
alpha := flag.String("alpha", "", "the first")
beta := flag.String("beta", "", "the second")
flag.Parse()
fmt.Println("ALPHA: " + *alpha)
fmt.Println("BETA: " + *beta)
}
The output of three different invocations where a "subcommand" is provided then look like this:
$ ./app --alpha 1 --beta 2 hi
ALPHA: 1
BETA: 2
$ ./app --alpha 1 hi --beta 2
ALPHA: 1
BETA:
$ ./app hi --alpha 1 --beta 2
ALPHA:
BETA:
How can a subcommand followed by a flag such as git status --short be recreated using the flags package?
答案1
得分: 3
我曾经遇到过同样的问题,这个对我有所帮助。
基本上,flag 包使用了 UNIX 的选项解析器 getopt(),在遇到第一个非选项后停止解析。
你也可以在上面的链接中找到解决方案。
英文:
I faced this same issue once, this helped me.
Basically, go flag package uses the UNIX option parser getopt() that stops parsing after the first non-option.
You can find the solution in the above link as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论