Golang眼镜蛇CLI-获取当前运行子命令

发布于 2025-01-28 09:27:32 字数 186 浏览 2 评论 0原文

眼镜蛇是否在某个地方存储了当前运行子命令的名称?例如,如果用户使用以下命令启动该工具,例如:

  • 工具子命令-flag1 -flag2等。
  • 工具-globalflag1 sub -command -flag1 -flag2

是否可以在程序内部确定哪个子命令在某些可变或方法中使用哪个子命令?

Does cobra store the name of currently running sub-command somewhere? E.g. if user started the tool with commands like:

  • tool sub-command -flag1 -flag2, etc.
  • tool -globalflag1 sub-command -flag1 -flag2

is it possible to determine inside the program which sub-command is used from some variable or method?

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

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

发布评论

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

评论(1

旧梦荧光笔 2025-02-04 09:27:32

COBRA命令结构提供了几种访问当前正在运行的命令的方法:

var RootCmd = &cobra.Command{
    ...
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
        fmt.Println("Executing:", cmd.CommandPath())
        fmt.Println("Executing:", cmd.CalledAs())
        fmt.Println("Executing:", cmd.CalledAs(), Args)
    },
}

假设有一个子命令subcmd注册和一个arg myarg,执行mycli subcmd myarg 返回:

Executing: mycli subcmd
Executing: subcmd
Executing: subcmd [myarg]

并且,如您的评论中所述,您可以通过在空间上拆分来获得命令路径的特定部分:

strings.Fields(cmd.CommandPath())[1]

The cobra Command struct offers a few methods to access what command is currently running:

var RootCmd = &cobra.Command{
    ...
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
        fmt.Println("Executing:", cmd.CommandPath())
        fmt.Println("Executing:", cmd.CalledAs())
        fmt.Println("Executing:", cmd.CalledAs(), Args)
    },
}

Assuming there's a subcommand subcmd registered and one arg myarg, executing mycli subcmd myarg returns:

Executing: mycli subcmd
Executing: subcmd
Executing: subcmd [myarg]

And, as mentioned in your comment, you can get a specific part of the command path by splitting on space:

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