如何使用 Groovy CliBuilder 解析未命名的 arg 值?

How to parse non-named arg values with Groovy CliBuilder?

我使用 CliBuilder 解析一些命名参数(h、t、c、n、s):

static main(args) {

  // http://mrhaki.blogspot.com/2009/09/groovy-goodness-parsing-commandline.html
  // http://docs.groovy-lang.org/latest/html/gapi/groovy/util/CliBuilder.html
  def cli = new CliBuilder(usage: 'hl7-benchmark -[t] type -[c] concurrency -[n] messages -[s] ip:port')

  cli.with {
      h longOpt: 'help',        'Show usage information'
      t longOpt: 'type',        args: 1, argName: 'type',        'mllp|soap'
      c longOpt: 'concurrency', args: 1, argName: 'concurrency', 'number of processes sending messages'
      n longOpt: 'messages',    args: 1, argName: 'messages',    'number of messages to be send by each process'
      s longOpt: 'ip:port',     args: 2, argName: 'ip:port',     'server IP address:server port',                 valueSeparator: ':'
  }

  def options = cli.parse(args)

调用命令行如下所示:hl7-benchmark -t xxx -c yyy -n zzz -s aaa:bbb

我需要在末尾添加一个可选属性,但我不希望它被命名,例如:

hl7-benchmark -t xxx -c yyy -n zzz -s aaa:bbb final_value_without_name

CliBuilder 可以吗?我找不到这方面的任何例子。

谢谢!

您可以简单地将其作为命令行的“arguments”部分获取:

def test(args) {
    def cli = new CliBuilder(usage: 'hl7-benchmark -[t] type -[c] concurrency -[n] messages -[s] ip:port')

    cli.with {
        h longOpt: 'help', 'Show usage information'
        t longOpt: 'type',        args: 1, argName: 'type',        'mllp|soap'
        c longOpt: 'concurrency', args: 1, argName: 'concurrency', 'number of processes sending messages'
        n longOpt: 'messages',    args: 1, argName: 'messages',    'number of messages to be send by each process'
        s longOpt: 'ip:port',     args: 2, argName: 'ip:port',     'server IP address:server port',                  valueSeparator: ':'
    }

    def options = cli.parse(args)
    def otherArguments = options.arguments()

    println options.t
    println options.c
    println options.n      
    println options.ss  // http://www.kellyrob99.com/blog/2009/10/04/groovy-clibuilder-with-multiple-arguments/#hide
    println otherArguments
}

test(['-t', 'xxx', '-c', 'yyy', '-n', 'zzz', '-s', 'aaa:bbb', 'final_value_without_name'])

以上给出:

xxx
yyy
zzz
[aaa, bbb]
[final_value_without_name]

如果您希望参数在 选项 之前也能被正确解析,您可以将 stopAtNonOption 设置为 false,如 CliBuilder argument without dash