Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse set default to multiple args

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?

like image 721
Oliver Avatar asked Sep 20 '13 19:09

Oliver


2 Answers

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])
like image 116
Robᵩ Avatar answered Oct 16 '22 08:10

Robᵩ


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!')
like image 34
Air Avatar answered Oct 16 '22 09:10

Air