add_argument 方法采用type 关键字参数。任何可调用对象都可以作为此参数的参数传递。
这是一个可以传递给add_argument 方法的类,这可能满足您的要求。
import argparse
class Arg(object):
def __init__(self, value):
self.value = value
if '=' in value:
self.value = value.split('=', 1)
def __str__(self):
return '{}=<{}>'.format(self.value[0], self.value[1]) if isinstance(self.value, list) else self.value
def __repr__(self):
if isinstance(self.value, list):
return repr('{}=<value>'.format(self.value[0]))
return '{}'.format(repr(self.value))
def __eq__(self, value):
return '{}'.format(repr(value)) == repr(self)
parser = argparse.ArgumentParser()
parser.add_argument('--param', default='ch1', choices=('ch1', 'ch2', 'ch3', 'ch4=<value>'), type=Arg)
args = parser.parse_args('--param ch4=123'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
args = parser.parse_args([])
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
args = parser.parse_args('--param ch3'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
输出;
choice ch4=<123>, value ['ch4', '123']
choice ch1, value 'ch1'
choice ch3, value 'ch3'
args.param 是Arg 的一个实例。 args.param.value 要么是 str,要么是 list,如果选择是 ch4='some_value'