问题
Currently I want Python's argparse module to only print out '1 - 65535' rather than {1, 2, 3, ... 65535}, but the documentation doesn't seem to provide any method for this. Any suggestions?
回答1:
You can alter the way defaults are formatted by setting the formatter_class option.
I'd subclass the HelpFormatter class to alter the way it formats your choices values. This class is officially an "implementation detail" but I doubt it'll change much with newer python versions.
The _metavar_formatter method formats the {1, 2, ..., 65535} string and your subclass could override that:
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
Another option is to not use the choices argument for such a large range, and instead define a new argument type.
This is just a callable, passed a string, that raises argparse.ArgumentTypeError, TypeError or ValueError if the string cannot be converted to the target type, or the converted value otherwise:
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
You can use this as the argument type like this:
parser.add_argument('foo', type=IntRange(1, 65536))
and adjust your help message to indicate what values are acceptable.
来源:https://stackoverflow.com/questions/11272806/pythons-argparse-choices-constrained-printing