How to pass flags as arguments in cobra (golang)?

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

How to pass flags as arguments in cobra (golang)?

问题

我正在使用cobra来创建一个CLI应用程序(app)。我需要实现一种行为,即我可以将标志作为参数传递。这些标志将通过exec.Command()进一步传递给另一个应用程序。app接收到的所有标志参数都必须被忽略,即不被识别为标志。

我不排除这是一种奇怪的行为。但如果有机会实现,我将非常感激。

与应用程序的交互示例:

> app --help
或者
> app --first --second

我希望参数(--help --first --second,以及其他所有参数)不被视为app的标志。

英文:

I am using cobra to create a CLI application (app). I need to implement a behavior in which I can pass flags as arguments. These flags will be passed|used further to another application via exec.Command(). All flag arguments passed to app must be ignored by the app itself, i.e. not recognized as flags.

I do not rule out that this is strange behavior. But if there is an opportunity to implement I will be grateful.

Examples of interaction with the application:

> app --help
or
> app --first --second

I want the arguments (--help --first --second, and all others) to not be taken as flags for app.

答案1

得分: 3

你可以在双破折号 -- 后面传递它们,按照惯例,双破折号之后的标志和参数不会被解释为主程序的参数和标志。除非你明确地使用它们,否则它们会被忽略。例如:

if len(pflag.Args()) != 0 {
	afterDash := pflag.Args()[pflag.CommandLine.ArgsLenAtDash():]
	fmt.Printf("破折号后的参数:%v\n", afterDash)
}
$ go run ./cmd/tpl/ -d yaml -- --foo --bar
破折号后的参数:[--foo --bar]

cobra 使用了 pflag 包 https://pkg.go.dev/github.com/spf13/pflag

英文:

You can pass them after a double dash -- which by convention indicates that following flags and args are not meant to be interpreted as args and flags for the main program. They are ignored unless you explicitly use them in some way. i.e.:

if len(pflag.Args()) != 0 {
	afterDash := pflag.Args()[pflag.CommandLine.ArgsLenAtDash():]
	fmt.Printf("args after dash: %v\n", afterDash)
}
$ go run ./cmd/tpl/ -d yaml -- --foo --bar
args after dash: [--foo --bar]

cobra is using the pflag package https://pkg.go.dev/github.com/spf13/pflag

huangapple
  • 本文由 发表于 2022年5月3日 18:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/72098388.html
匿名

发表评论

匿名网友

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

确定