argparse zero-length switch

Carl Banks pavlovevidence at gmail.com
Fri Oct 14 02:05:26 EDT 2011


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.

Carl Banks



More information about the Python-list mailing list