2

How does one use pflag while also using other packages that use flag?

Some of these packages define flags for the flag package (e.g. in their init functions) - and require flag.Parse() to be called.

Defining flags using the pflag package, require pflag.Parse() to be called.

One of the calls to flag.Parse() and pflag.Parse() will fail when arguments are mixed.

How does one use pflag with other packages that use flag?

Ziffusion
  • 8,779
  • 4
  • 29
  • 57
  • 4
    IMHO packages shouldn't call `flag.Parse` and instead provide package specific way to configure them. calling `flag.Parse` is application (package main) responsibility. If a package that you want to use calls `flag.Parse` file a bug. – kostya Dec 03 '15 at 02:45
  • umm ... no that is not what the question is stating. The call to flag.Parse() or pflag.Parse() would happen in main(). The problem I am getting at is that if you use pflag in your package, then you cannot use *any other* package that happens to use flag. Because then you would need to make a call to both flag.Parse() and pflag.Parse() in main() - and one or both will fail. – Ziffusion Dec 03 '15 at 15:48

3 Answers3

4

I have found two approach for this.

  1. One with pflags AddGoFlags(). IE.

    f := pflag.NewFlagSet("goFlags", pflag.ExitOnError)
    f.AddGoFlagSet(flag.CommandLine)
    f.Parse([]string{
       "--v=10", // Your go flags that will be pass to other programs.
    })
    flag.Parse()
    
  2. Another approach you can use. This is not by the book but i have seen some used this.. get the flag valu by another pflag.

    pflag.StringVar(&f, "f", "**", "***")
    pflag.Parse()
    

Set the value as flag value.

    flag.Set("v", f)
    flag.Parse()

and you are good to go..

sadlil
  • 3,077
  • 5
  • 23
  • 36
0

I got a response from a maintainer for pflag.

The solution is to "import" all flags defined for flag into pflag, and then make a call to pflag.Parse() alone.

pflag provides a convenience function called AddGoFlagSet() to accomplish this.

Ziffusion
  • 8,779
  • 4
  • 29
  • 57
-1

How does one use pflag with other packages that use flag?

You cannot. It is either or. plfag is a drop-in replacement for flag, not an addon.

Volker
  • 40,468
  • 7
  • 81
  • 87
  • Yes - I get that. So, basically, if you use pflag in your own package, you cannot use *any other* package that uses flag? Seems like a pretty crippling requirement. – Ziffusion Dec 03 '15 at 15:43