getopt with negative numbers?
Steven Bethard
steven.bethard at gmail.com
Thu Sep 27 19:06:25 EDT 2007
Casey wrote:
> Is there an easy way to use getopt and still allow negative numbers as
> args?
[snip]
> Alternatively, does optparse handle this?
Peter Otten wrote:
> 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']
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
STeVe
More information about the Python-list
mailing list