getopt-like behavior in Go

前端 未结 9 707
南笙
南笙 2021-02-07 11:33

How do I nicely parse a list of program parameters and automate handling \"--help\" and/or \"--version\" (such as \"program [-d value] [--abc] [FILE1]\") in Go?

相关标签:
9条回答
  • 2021-02-07 11:59

    I made it just for you:

    package main
    
    import (
      "fmt";
      "os"
    )
    
    func main() {
      for i, arg := range os.Args {
        if arg == "-help" {
          fmt.Printf ("I need somebody\n")
        }else if arg == "-version" {
          fmt.Printf ("Version Zero\n")
        } else {
          fmt.Printf("arg %d: %s\n", i, os.Args[i])
        }
      }
    }
    

    see also https://play.golang.org/p/XtNXG-DhLI

    Test:

    $ ./8.out -help -version monkey business
    I need somebody
    Version Zero
    arg 3: monkey
    arg 4: business
    
    0 讨论(0)
  • 2021-02-07 12:00

    One can simply use Golang own library "flag".

    It has pretty much code to create CLI like application in GoLang. for Example :

    srcDir := flag.String("srcDir", "", "Source directory of the input csv file.")
    

    The above String method of flag library will expect one argument from command prompt.

    Go to https://golang.org/pkg/flag/ for more reading.

    Happy Learning...

    0 讨论(0)
  • 2021-02-07 12:05

    Use the 'flag' package: http://golang.org/pkg/flag/. It doesn't do double-dash arguments, however. There isn't anything that exactly mimics GNU getopt behaviour (yet.)

    0 讨论(0)
提交回复
热议问题