2

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.

AnkurVj
  • 7,958
  • 10
  • 43
  • 55
  • This kind of option isn't standard (I don't know about any app which use this). It is also less readable since the second argument (eg the 45) isn't expected to be related to the range option. I don't think there is a way doing it without patching scopt. – roterl Sep 27 '14 at 22:36

2 Answers2

1

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.

0__
  • 66,707
  • 21
  • 171
  • 266
  • Thank you for going through the source code to determine that. I guess I'll just go with the `--min --max` approach for now. – AnkurVj Sep 28 '14 at 12:34
0

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}")
Kombajn zbożowy
  • 8,755
  • 3
  • 28
  • 60