getopt with negative numbers?

Peter Otten __peter__ at web.de
Thu Sep 27 19:34:04 CEST 2007


Casey wrote:

> Is there an easy way to use getopt and still allow negative numbers as
> args?  I can easily write a workaround (pre-process the tail end of
> the arguments, stripping off any non-options including negative
> numbers into a separate sequence and ignore the (now empty) args list
> returned by getopt, but it would seem this is such a common
> requirement that there would be an option to treat a negative value as
> an argument.  Note that this is only a problem if the first non-option
> is a negative value, since getopt stops processing options as soon as
> it identifies the first argument value.
> 
> Alternatively, does optparse handle this?  I haven't used optparse (I
> know it is more powerful and OO, but you tend to stick with what you
> know, especially when it is part of my normal python programming
> template), but if it handles negative numbers I'm willing to learn it.

optparse can handle options with a negative int value; "--" can be used to
signal that no more options will follow:

>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-a", type="int")
<Option at 0xb7d6fd8c: -a>
>>> options, args = parser.parse_args(["-a", "-42", "--", "-123"])
>>> options.a
-42
>>> args
['-123']

Without the "--" arg you will get an error:

>>> parser.parse_args(["-123"])
Usage:  [options]

: error: no such option: -1
$

Peter



More information about the Python-list mailing list