Argparse:如何接受不同“类型”的参数
我想要接受以下格式的参数:
python3 test.py -r SERVICE=100,101,102 -r SERVICE2=1,2,3,4,5
(-r REPO=REV#,REV#,etc... -r etc...)
到目前为止,我已经做了以下工作(添加了参数 -r,并定义了类型 revs)。它应该返回两个列表,但这可能会有问题。
import argparse
def revs(s):
try:
REPO, REVISIONS = map(str, s.split('='))
REVISIONS = map(int, REVISIONS.split(','))
return REPO, REVISIONS
except:
raise argparse.ArgumentTypeError("Must be format -r REPO=REV,REV,etc.. e.g. SERVICES=181449,181447")
parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)
当我用上面的代码运行时,出现了以下错误:
Traceback (most recent call last):
File "test.py", line 11, in <module>
parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)
File "/usr/local/lib/python3.3/argparse.py", line 1317, in add_argument
raise ValueError('%r is not callable' % (type_func,))
ValueError: 'revs' 不能被调用
1 个回答
20
你想要
parser.add_argument('-r', type=revs, ...)
而不是
parser.add_argument('-r', type='revs', ...)
这个type
参数必须是一个可以调用的对象——因为字符串不能被调用,所以它们不能用作type
。