如何在眼镜蛇 golang 中使用子命令?

我找不到使用该示例的方法


./client echo --times 10 "coucou" 

./client  --times 10 "coucou" echo

没办法使用它...抱歉我的错误。


最好的问候,尼古拉斯


    func main() {

    var echoTimes int


    var cmdEcho = &cobra.Command{

        Use:   "echo [string to echo]",

        Short: "Echo anything to the screen",

        Long:  `echo is for echoing anything back.

        Echo works a lot like print, except it has a child command.

        `,

        Run: func(cmd *cobra.Command, args []string) {

            fmt.Println("Print: " + strings.Join(args, " "))

        },

    }


    var cmdTimes = &cobra.Command{

        Use:   "times [# times] [string to echo]",

        Short: "Echo anything to the screen more times",

        Long:  `echo things multiple times back to the user by providing

        a count and a string.`,

        Run: func(cmd *cobra.Command, args []string) {

            for i:=0; i < echoTimes; i++ {

                fmt.Println("Echo: " + strings.Join(args, " "))

            }

        },

    }


    cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

    var rootCmd = &cobra.Command{Use: "app"}

    rootCmd.AddCommand(cmdEcho)

    cmdEcho.AddCommand(cmdTimes)

    rootCmd.Execute()

}


慕仙森
浏览 186回答 2
2回答

守着一只汪

如果times是命令,则不应以“ --”作为前缀。您可以在其中看到的示例cobra_test.go展示了以下times用途:echo times -j 99 one twoecho times -s again -c test here

翻过高山走不出你

例如,如果您执行的文件名为app,只需运行$./app echo times -t 3 hello&nbsp;Echo: hello&nbsp;Echo: hello&nbsp;Echo: hello或者$./app echo times --times=3 helloEcho: helloEcho: helloEcho: hello
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go