简体   繁体   English

如何在眼镜蛇(golang)中将标志传递为 arguments?

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

I am using cobra to create a CLI application ( app ).我正在使用cobra创建 CLI 应用程序 ( app )。 I need to implement a behavior in which I can pass flags as arguments .我需要实现一种行为,我可以将标志作为 arguments 传递 These flags will be passed|used further to another application via exec.Command() .这些标志将通过exec.Command()进一步传递给另一个应用程序。 All flag arguments passed to app must be ignored by the app itself, ie not recognized as flags.传递给应用程序的所有标志 arguments 必须被应用程序本身忽略,即不被识别为标志。

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 .我希望 arguments( --help --first --second和所有其他)不被视为app的标志。

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.除非您以某种方式明确使用它们,否则它们将被忽略。 ie: IE:

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眼镜蛇正在使用 pflag package https://pkg.go.dev/github.com/spf13/pflag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM