Python的argparse选择限制了打印 [英] Python's argparse choices constrained printing
问题描述
当前,我希望Python的argparse模块仅输出'1-65535'而不是{1,2,3,... 65535},但是文档似乎没有为此提供任何方法.有什么建议吗?
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?
推荐答案
You can alter the way defaults are formatted by setting the formatter_class
option.
我将 HelpFormatter类子类化为更改格式化choices
值的方式.此类正式是实现细节",但我怀疑它会在较新的python版本中发生很大变化.
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.
_metavar_formatter
方法格式化{1, 2, ..., 65535}
字符串,您的子类可以覆盖它:
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
另一种选择是不在如此大的范围内使用choices
参数,而是定义一个新的
Another option is to not use the choices
argument for such a large range, and instead define a new argument type.
这只是一个可调用的,传递的字符串,如果无法将字符串转换为目标类型,则引发argparse.ArgumentTypeError
,TypeError
或ValueError
,否则将转换为值:
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.
这篇关于Python的argparse选择限制了打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!