Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept a range of numbers in the form of 0-5 using Python's argparse?

Using argparse, is there a way to accept a range of numbers and convert them into a list?

For example:

python example.py --range 0-5

Is there some way input a command line argument in that form and end up with:

args.range = [0,1,2,3,4,5]

And also have the possibility to input --range 2 = [2]?

like image 588
Takkun Avatar asked Jun 28 '11 19:06

Takkun


People also ask

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .

What does Argparse ArgumentParser ()?

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object: args = parser. parse_args() print(args.


2 Answers

You could just write your own parser in the type argument, e.g.

from argparse import ArgumentParser, ArgumentTypeError
import re

def parseNumList(string):
    m = re.match(r'(\d+)(?:-(\d+))?$', string)
    # ^ (or use .split('-'). anyway you like.)
    if not m:
        raise ArgumentTypeError("'" + string + "' is not a range of number. Expected forms like '0-5' or '2'.")
    start = m.group(1)
    end = m.group(2) or start
    return list(range(int(start,10), int(end,10)+1))

parser = ArgumentParser()
parser.add_argument('--range', type=parseNumList)

args = parser.parse_args()
print(args)
~$ python3 z.py --range m
usage: z.py [-h] [--range RANGE]
z.py: error: argument --range: 'm' is not a range of number. Expected forms like '0-5' or '2'.

~$ python3 z.py --range 2m
usage: z.py [-h] [--range RANGE]
z.py: error: argument --range: '2m' is not a range of number. Expected forms like '0-5' or '2'.

~$ python3 z.py --range 25
Namespace(range=[25])

~$ python3 z.py --range 2-5
Namespace(range=[2, 3, 4, 5])
like image 147
kennytm Avatar answered Oct 18 '22 18:10

kennytm


You can just use a string argument and then parse it with range(*rangeStr.split(',')).

like image 23
phihag Avatar answered Oct 18 '22 18:10

phihag