Reputation: 3682
I want use argparse to specify a option that take three integer values: like specifying a range: start, end, step.
parser.add_argument('--range', nargs=3, metavar=('start', 'end', 'step'),
type=int, help="specify a range')
However, it is not clear to me how to provide default values to all three values. Do I need to define it as string and parse it myself?
Upvotes: 19
Views: 20083
Reputation: 168616
Does this work for you?
parser.add_argument('--range', default=[4,3,2],
nargs=3, metavar=('start', 'end', 'step'),
type=int, help='specify a range')
Demo program:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--range', default=[4,3,2], nargs=3, metavar=('start', 'end', 'step'),
type=int, help='specify a range')
print parser.parse_args([])
# prints Namespace(range=[4, 3, 2])
Upvotes: 23
Reputation: 8595
When using nargs
, to provide multiple default values, define them in a list - see the third code snippet of this section of the docs, which contains the following example:
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
Upvotes: 7