我如何很好地分析一个列表中的程序的参数和自动化的处理"--帮助"和/或"--的版本"(例如"program [-d value] [--abc] [FILE1]")在去吗?

有帮助吗?

解决方案 5

我做到了只为你:

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])
    }
  }
}

也参见 https://play.golang.org/p/XtNXG-DhLI

测试:

$ ./8.out -help -version monkey business
I need somebody
Version Zero
arg 3: monkey
arg 4: business

其他提示

使用 '标志' 包: http://golang.org/pkg/flag/ 。它没有做双横线的论点,但是。有没有什么恰好模仿GNU getopt的行为(还)

谷歌已经创建了一个 getopt的包(import "github.com/pborman/getopt"),其提供更标准的命令行解析(VS的 '标志' 包)。

package main

import (
    "fmt"
    "os"
    "github.com/pborman/getopt"
)

func main() {
    optName := getopt.StringLong("name", 'n', "", "Your name")
    optHelp := getopt.BoolLong("help", 0, "Help")
    getopt.Parse()

    if *optHelp {
        getopt.Usage()
        os.Exit(0)
    }

    fmt.Println("Hello " + *optName + "!")
}

$ ./hello --help
Usage: hello [--help] [-n value] [parameters ...]
     --help        Help
 -n, --name=value  Your name

$ ./hello --name Bob
Hello Bob!

从“命令行 UI”部分,您有几个能够解析的库 getopt-long 参数.

我尝试过,用 Go1.0.2:

例子:

package main

import (
    "fmt"
    goopt "github.com/droundy/goopt"
)

func main() {
    fmt.Println("flag")
    goopt.NoArg([]string{"--abc"}, "abc param, no value", noabc)

    goopt.Description = func() string {
        return "Example program for using the goopt flag library."
    }
    goopt.Version = "1.0"
    goopt.Summary = "goopt demonstration program"
    goopt.Parse(nil)
}

func noabc() error {
    fmt.Println("You should have an --abc parameter")
    return nil
}

提供的其他默认参数 goopt:

 --help               Display the generated help message (calls Help())
 --create-manpage     Display a manpage generated by the goopt library (uses Author, Suite, etc)
 --list-options       List all known flags

去标志 是的非常完整、BSD获得许可,并有一个清楚 .

var opts struct {
      DSomething string `short:"d" description:"Whatever this is" required:"true"`
      ABC bool `long:"abc" description:"Something"`
}

fileArgs, err := flags.Parse(&opts)

if err != nil {
    os.Exit(1)
}

另一种选择是 Kingping 它提供了所有你为标准的东西从现代的期望支持命令行解析库。它以多种格式,子命令,要求,类型,默认设置等方面--help它也仍处于开发阶段。这似乎是其他建议这里已经有一段时间没有更新了。

package main

import (
  "os"
  "strings"
  "gopkg.in/alecthomas/kingpin.v2"
)

var (
  app      = kingpin.New("chat", "A command-line chat application.")
  debug    = app.Flag("debug", "Enable debug mode.").Bool()
  serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()

  register     = app.Command("register", "Register a new user.")
  registerNick = register.Arg("nick", "Nickname for user.").Required().String()
  registerName = register.Arg("name", "Name of user.").Required().String()

  post        = app.Command("post", "Post a message to a channel.")
  postImage   = post.Flag("image", "Image to post.").File()
  postChannel = post.Arg("channel", "Channel to post to.").Required().String()
  postText    = post.Arg("text", "Text to post.").Strings()
)

func main() {
  switch kingpin.MustParse(app.Parse(os.Args[1:])) {
  // Register user
  case register.FullCommand():
    println(*registerNick)

  // Post message
  case post.FullCommand():
    if *postImage != nil {
    }
    text := strings.Join(*postText, " ")
    println("Post:", text)
  }
}

和所述--help输出:

$ chat --help
usage: chat [<flags>] <command> [<flags>] [<args> ...]

A command-line chat application.

Flags:
  --help              Show help.
  --debug             Enable debug mode.
  --server=127.0.0.1  Server address.

Commands:
  help [<command>]
    Show help for a command.

  register <nick> <name>
    Register a new user.

  post [<flags>] <channel> [<text>]
    Post a message to a channel.

我想你想要的是docopt。我只是指你到一个较早的答案我张贴的细节。

作为一个简单的图书馆,你有自八月2017 github.com/rsc/getopt

使用定义的标志,作为通常的带包装的标志。然后引入任何通过调用的别名 getopt.Alias:

getopt.Alias("v", "verbose")

或者叫 getopt.Aliases 定义一个列表,别名:

getopt.Aliases(
    "v", "verbose",
    "x", "xylophone",
)

并且:

在一般去标志的分析适用于新的程序,因为它不是作迂腐的有关数量的破折号用来引用一个标志(你可以写 -verbose--verbose, 和程序不健).

这个包裹是指被使用的情况下,为传统原因,重要的是要使用完全 getopt(3) 语法,例如当改写在去现有的工具,已经使用 getopt(3).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top