【发布时间】:2022-01-11 01:56:46
【问题描述】:
使用 cobra,如果我的应用在没有特定操作(但参数)的情况下被调用,我想运行一个默认命令:
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "mbmd",
Short: "ModBus Measurement Daemon",
Long: "Easily read and distribute data from ModBus meters and grid inverters",
Run: func(cmd *cobra.Command, args []string) {
run(cmd, args)
},
}
但是,由于根命令没有所有参数,因此子命令失败了,因为它现在显然知道子命令的参数:
❯ go run main.go -d sma:126@localhost:5061 --api 127.1:8081 -v
Error: unknown shorthand flag: 'd' in -d
相对于:
❯ go run main.go run -d sma:126@localhost:5061 --api 127.1:8081 -v
2019/07/29 20:58:10 mbmd unknown version (unknown commit)
如何以编程方式实例化/调用子命令?
【问题讨论】:
-
致电
run()。 Cobra 中的每个命令都只是调用一个函数。您可以从多个 cobra 命令调用相同的函数。 -
和我一样?这仅尊重根命令参数,但不尊重运行命令的参数:/
-
您现在(2021 年 10 月)有两种可能的解决方法。见my answer below。