Golang的flag包在遇到非标志参数时停止解析。

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

Golang flag package stops parsing when encountering a non-flag

问题

内置的flags包在遇到进程的第一个非标志参数时似乎会中断解析。考虑以下应用程序:

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. )
  6. func main() {
  7. alpha := flag.String("alpha", "", "the first")
  8. beta := flag.String("beta", "", "the second")
  9. flag.Parse()
  10. fmt.Println("ALPHA: " + *alpha)
  11. fmt.Println("BETA: " + *beta)
  12. }

在提供了一个“子命令”的三个不同调用的输出如下所示:

  1. $ ./app --alpha 1 --beta 2 hi
  2. ALPHA: 1
  3. BETA: 2
  4. $ ./app --alpha 1 hi --beta 2
  5. ALPHA: 1
  6. BETA:
  7. $ ./app hi --alpha 1 --beta 2
  8. ALPHA:
  9. 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:

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. )
  6. func main() {
  7. alpha := flag.String("alpha", "", "the first")
  8. beta := flag.String("beta", "", "the second")
  9. flag.Parse()
  10. fmt.Println("ALPHA: " + *alpha)
  11. fmt.Println("BETA: " + *beta)
  12. }

The output of three different invocations where a "subcommand" is provided then look like this:

  1. $ ./app --alpha 1 --beta 2 hi
  2. ALPHA: 1
  3. BETA: 2
  4. $ ./app --alpha 1 hi --beta 2
  5. ALPHA: 1
  6. BETA:
  7. $ ./app hi --alpha 1 --beta 2
  8. ALPHA:
  9. 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.

huangapple
  • 本文由 发表于 2022年12月30日 13:52:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/74958571.html
匿名

发表评论

匿名网友

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

确定