Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create argument of type "list of pairs" with argparse?

I need to let the end user of my python script types something like:

script.py -sizes <2,2> <3,3> <6,6>

where each element of the -sizes option is a pair of two positive integers. How can I achieve this with argparse ?

like image 249
Manuel Selva Avatar asked Nov 03 '15 12:11

Manuel Selva


People also ask

How do you add arguments in Argparse?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages.


1 Answers

Define a custom type:

def pair(arg):
    # For simplity, assume arg is a pair of integers
    # separated by a comma. If you want to do more
    # validation, raise argparse.ArgumentError if you
    # encounter a problem.
    return [int(x) for x in arg.split(',')]

then use this as the type for a regular argument:

p.add_argument('--sizes', type=pair, nargs='+')

Then

>>> p.parse_args('--sizes 1,3 4,6'.split())
Namespace(sizes=[[1, 3], [4, 6]])
like image 137
chepner Avatar answered Sep 28 '22 02:09

chepner