如何将标志作为眼镜蛇(Golang)的参数传递?

发布于 2025-01-25 22:50:00 字数 535 浏览 1 评论 0 原文

我正在使用 cobra 创建一个CLI应用程序( app )。我需要实施一种行为,我可以将标志作为参数。这些标志将通过 app 的标志参数必须被 app 本身忽略,即不被识别为标志。

我不排除这是奇怪的行为。但是,如果有机会实施,我将感谢。

与应用程序互动的示例:

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

我希望参数( - help-第一秒和所有其他参数)不作为 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半夏半凉 2025-02-01 22:50:00

您可以在Double Dash - 之后传递它们,该通过惯例表明以下标志和args不应将其解释为主程序的ARG和标志。除非您以某种方式明确使用它们,否则它们将被忽略。 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]

眼镜蛇正在使用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

若沐 2025-02-01 22:50:00

这是一个古老的问题,但也许有人会从中受益。

Cobras命令结构具有一个称为 disableflagparsing bool 的变量,默认情况下它是 false 。将设置为 true 时,眼镜蛇将停止解析标志,并将其传递到运行或任何其他类似运行的命令中的args。 - > 运行func(cmd *命令,args [] string)

vor from Documentation:

禁用Flagparsing禁用标志解析​​。如果这是正确的,则所有标志将作为参数传递给命令。

it's an old question but maybe someone will benefit from it.

Cobras Command struct has a variable called DisableFlagParsing bool, by default it's false. When set to true, Cobra will stop parsing flags and pass them to args in the Run or any other Run-like command. -> Run func(cmd *Command, args []string)

Quote from documentation:

DisableFlagParsing disables the flag parsing. If this is true all flags will be passed to the command as arguments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文