Numeric command-line options vs. negative-number arguments

Steven Bethard steven.bethard at gmail.com
Fri Sep 28 00:33:47 EDT 2007


Ben Finney wrote:
> Steven Bethard <steven.bethard at gmail.com> writes:
> 
>> In most cases, argparse (http://argparse.python-hosting.com/)
>> supports negative numbers right out of the box, with no need to use
>> '--':
>>
>>     >>> import argparse
>>     >>> parser = argparse.ArgumentParser()
>>     >>> parser.add_argument('-a', type=int)
>>     >>> parser.add_argument('b', type=int)
>>     >>> args = parser.parse_args('-a -42 -123'.split())
>>     >>> args.a
>>     -42
>>     >>> args.b
>>     -123
> 
> That would be irritating. I've used many programs which have numbers
> for their options because it makes the most sense, e.g. 'mpage' to
> indicate number of virtual pages on one page, or any number of
> networking commands that use '-4' and '-6' to specify IPv4 or IPv6.

Did you try it and find it didn't work as you expected? Numeric options 
seem to work okay for me::

     >>> import argparse
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('-1', dest='one', action='store_true')
     >>> args = parser.parse_args(['-1'])
     >>> args.one
     True

Argparse knows what your option flags look like, so if you specify one, 
it knows it's an option.  Argparse will only interpret it as a negative 
number if you specify a negative number that doesn't match a known option.

STeVe



More information about the Python-list mailing list