argparse zero-length switch
Peter Otten
__peter__ at web.de
Fri Oct 14 03:41:26 EDT 2011
Carl Banks wrote:
> Is it possible to specify a zero-length switch? Here's what I mean.
>
> I have a use case where some users would have to enter a section name on
> the command line almost every time, whereas other users (the ones using
> only one section) will never have to enter the section name. I don't want
> to burden users with only one "section" to always enter the section name
> as a required argument, but I also want to make it as convenient as
> possible to enter the section name for those who need to.
>
> My thought, on the thinking that practicality beats purity, was to create
> a zero-length switch using a different prefix character (say, @) to
> indicate the section name. So instead of typing this:
>
> sp subcommand -s abc foo bar
>
> they could type this:
>
> sp subcommand @abc foo bar
>
> Admittedly a small benefit. I tried the following but argparse doesn't
> seem to do what I'd hoped:
>
> p = argparse.ArgumentParser(prefix_chars='-@')
> p.add_argument('@',type=str,dest='section')
> ar = p.parse_args(['@abc'])
>
> This throws an exception claiming unrecognized arguments.
>
> Is there a way (that's not a hack) to do this? Since the current behavior
> of the above code seems to do nothing useful, it could be added to
> argparse with very low risk of backwards incompatibility.
If the number of positional arguments is otherwise fixed you could make
section a positional argument with nargs="?"
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("section", nargs="?")
>>> _ = parser.add_argument("foo")
>>> _ = parser.add_argument("bar")
>>> parser.parse_args(["alpha", "beta"])
Namespace(bar='beta', foo='alpha', section=None)
>>> parser.parse_args(["alpha", "beta", "gamma"])
Namespace(bar='gamma', foo='beta', section='alpha')
More information about the Python-list
mailing list