简体   繁体   English

为什么 Cobra 标志在此代码中不起作用

[英]Why is Cobra flags not working in this code

How to get flags to work in Cobra using Local flags如何使用本地标志在 Cobra 中使用标志

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    myCmd := &cobra.Command{
        Use: "myaction",
        Run: func(cmd *cobra.Command, args []string) {
            if len(args) == 1 {
                flags := cmd.Flags()
                var strTmp string
                flags.StringVarP(&strTmp, "test", "t", "", "Source directory to read from")
                fmt.Println(strTmp)
            }
        },
    }

    myCmd.Execute()
}

Error错误

go run main.go myaction --test="hello"
Error: unknown flag: --test
Usage:
  myaction [flags]

Flags:
  -h, --help   help for myaction

The Run part of the command gets executed only after the Execute is called on the command (you can also have a prerun-hook .)该命令的Run部分仅在命令上调用Execute后才会执行(您也可以有一个prerun-hook 。)

So in your case when execute is called the runtime doesn't know about the flag.因此,在您调用 execute 的情况下,运行时不知道该标志。 We should add the flags before the Execute is called on the command to make the runtime aware of it.我们应该在命令上调用Execute之前添加标志,以使运行时知道它。

Code代码

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    var strTmp string
    myCmd := &cobra.Command{
        Use: "myaction",
        Run: func(cmd *cobra.Command, args []string) {
            if len(args) == 1 {
                fmt.Println(strTmp)
            }
        },
    }
    myCmd.Flags().StringVarP((&strTmp), "test", "t", "", "Source directory to read from")
    myCmd.Execute()
}

Output Output

⇒  go run main.go myaction --test "hello"
hello

But there is an alternate solution to this, when you want to add the flags based on a condition.但是,当您想根据条件添加标志时,还有另一种解决方案。 You can set DisableFlagParsing to true and parse it later.您可以将DisableFlagParsing设置为true并稍后对其进行解析。

Code代码

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    myCmd := &cobra.Command{
        Use: "myaction",
        RunE: func(cmd *cobra.Command, args []string) error {
            if len(args) > 1 {
                flags := cmd.Flags()
                var strTmp string

                // Add the flag
                flags.StringVarP(&strTmp, "test", "t", "", "Source directory to read from")
                
                // Enable the flag parsing
                cmd.DisableFlagParsing = false

                // Parse the flags
                if err := cmd.ParseFlags(args); err != nil {
                    return err
                }

                fmt.Println(strTmp)
            }

            return nil
        },
    }

    // Disable flag parsing
    myCmd.DisableFlagParsing = true
    myCmd.Execute()
}

Output Output

⇒  go run main.go myaction --test "hello"
hello

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

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