在命令行中解析 Golang 标志位参数之后的参数。

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

Golang flag parsing after an argument on command line

问题

我正在解析命令行参数。我使用以下代码:

var flagB = flag.Bool("b", false, "boolflag")

func main() {
    flag.Parse()
    
    fmt.Println(flag.NArg())
    fmt.Println("-b", *flagB)
}

当我像这样执行二进制文件时:

> test -b "random"

我得到了预期的输出,因为有一个参数,并且标志被设置为 true:

1
-b true

然而,当我以另一种方式执行二进制文件时:

> test "random" -b

我得到了这个输出:

2
-b false

现在,标志不再被识别为标志,而是作为另一个参数。

为什么会这样?是否有一个规定,标志应该先出现,然后是参数?我一直以为“GNU方式”传递和解析参数的方式是:在二进制文件之后的位置保留给必需参数。然后,您可以放置可选参数和标志。

英文:

I am parsing command-line arguments. I use the following code:

var flagB = flag.Bool("b", false, "boolflag")

func main() {
	flag.Parse()
	
	fmt.Println(flag.NArg())
	fmt.Println("-b", *flagB)
}

When I execute the binary like this:

> test -b "random"

I get the expected output, becuase there is one argument, and the flag is set:

1
-b true

However, when I execute the binary the other way around:

> test "random" -b

I get this:

2
-b false

Now, the flag isn't recodnized any more as flag, but as another argument.

Why is it that way? Is there a definition that flags come first and then the arguments? I always thought that the "GNU-way" of passing and parsing arguments is: The first places after the binary are reserved for mandatory arguments. And after that you can put optional arguments and flags.

答案1

得分: 15

flag包不使用GNU解析规则。这些规则在flag包的文档中有解释(http://golang.org/pkg/flag/)。你的问题在那里得到了回答:

在第一个非标志参数之前(“-”是非标志参数)或终止符“--”之后,标志解析停止。

英文:

The flag package does not use GNU parsing rules. The rules are explained in the documentation for flag the package. Your question is answered there:

> Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--".

huangapple
  • 本文由 发表于 2014年8月12日 00:59:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/25248534.html
匿名

发表评论

匿名网友

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

确定