开发者

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 inp开发者_JAVA技巧ut --range 2 = [2]?


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])


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜