您可以通过设置来更改默认格式的方式formatter_class option.
我会子类化帮助格式化程序类改变它格式化你的方式choices
价值观。这个类正式是一个“实现细节”,但我怀疑它会随着新的 python 版本而发生很大变化。
The _metavar_formatter method格式化{1, 2, ..., 65535}
string 和你的子类可以覆盖它:
class RangeChoiceHelpFormatter(HelpFormatter):
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
result = '{%s .. %s}' % (min(action.choices), max(action.choices])
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
另一种选择是not使用choices
如此大范围的参数,而是定义一个新的参数类型.
这只是一个可调用的,传递一个字符串,引发argparse.ArgumentTypeError
, TypeError
or ValueError
如果字符串无法转换为目标类型,或者转换后的值,否则:
class IntRange(object):
def __init__(self, start, stop=None):
if stop is None:
start, stop = 0, start
self.start, self.stop = start, stop
def __call__(self, value):
value = int(value)
if value < self.start or value >= self.stop:
raise argparse.ArgumentTypeError('value outside of range')
return value
您可以使用它作为参数类型,如下所示:
parser.add_argument('foo', type=IntRange(1, 65536))
并调整您的帮助消息以指示哪些值是可以接受的。