AnkurVj
AnkurVj

Reputation: 8218

Parsing options that take more than one value with scopt in scala

I am using scopt to parse command line arguments in scala. I want it to be able to parse options with more than one value. For instance, the range option, if specified, should take exactly two values.

--range 25 45

Coming, from python background, I am basically looking for a way to do the following with scopt instead of python's argparse:

    parser.add_argument("--range", default=None, nargs=2, type=float,
                         metavar=('start', 'end'),
                         help=(" Foo bar start and stop "))

I dont think minOccurs and maxOccurs solves my problem exactly, nor the key:value example in its help.

Upvotes: 2

Views: 2255

Answers (2)

Kombajn zbożowy
Kombajn zbożowy

Reputation: 10703

It should be ok if only your values are delimited with something else than a space...

--range 25-45

... although you need to split them manually. Parse it with something like:

opt[String]('r', "range").action { (x, c) =>
  val rx = "([0-9]+)\\-([0-9]+)".r
  val rx(from, to) = x
  c.copy(from = from.toInt, to = to.toInt)
}
// ...
println(s" Got range ${parsedArgs.from}..${parsedArgs.to}")

Upvotes: 0

0__
0__

Reputation: 67310

Looking at the source code, this is not possible. The Read type class used has a member tuplesToRead, but it doesn't seem to be working when you force it to 2 instead of 1. You will have to make a feature request, I guess, or work around this by using --min 25 --max 45, or --range '25 45' with a custom Read instance that splits this string into two parts. As @roterl noted, this is not a standard way of parsing.

Upvotes: 1

Related Questions