我想知道是否有人想过使用argparse来获得一系列值,如0-10,而不使用任何其他库?
示例:
>>python script.py --range 0-10
将创建一个列表作为
arg.range=[0,1,2,3,4,5,6,7,8,9,10]
您可以用'-'拆分参数,并将其传递给范围函数,范围函数将依次传递给列表。这将打印序列
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--range")
args = parser.parse_args()
before, after = args.range.split('-')
print(list(range(int(before), int(after)+1)))
如果我们稍微改变输入要求,我们可以提供可变数量的整数,充分利用range
的幂。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-r','--range', type=int, nargs='+')
args = parser.parse_args()
print(args)
if len(args.range)>3:
parser.error('no more than 3 arguments, please')
elif len(args.range)==2: # or use nargs=2
start, stop = args.range
alist = list(range(start, stop))
else:
# more general case,
alist = list(range(*args.range))
print(alist)
样本运行
0838:~/mypy$ python3 stack65084869.py -h
usage: stack65084869.py [-h] [-r RANGE [RANGE ...]]
optional arguments:
-h, --help show this help message and exit
-r RANGE [RANGE ...], --range RANGE [RANGE ...]
0842:~/mypy$ python3 stack65084869.py 0 10
usage: stack65084869.py [-h] [-r RANGE [RANGE ...]]
stack65084869.py: error: unrecognized arguments: 0 10
0842:~/mypy$ python3 stack65084869.py --range 0 10
Namespace(range=[0, 10])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0842:~/mypy$ python3 stack65084869.py --range 10
Namespace(range=[10])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0843:~/mypy$ python3 stack65084869.py --range 10 -1 -1
Namespace(range=[10, -1, -1])
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
0847:~/mypy$ python3 stack65084869.py --range 10 -1 -1 0
Namespace(range=[10, -1, -1, 0])
usage: stack65084869.py [-h] [-r RANGE [RANGE ...]]
stack65084869.py: error: no more than 3 arguments, please