在深入研究 argparse 源代码之后,我构建了一个hack来删除多余的{cmd1,...}
选择列表。
hack 实现了一个自定义帮助格式化程序,它HelpFormatter
在处理子解析器操作时修改了格式化方法。具体来说,它删除了子命令参数组中的子解析器metavar
和
help
行,并删除了这些子命令的额外缩进。
请小心使用。
python 3版本,用python3.6测试
from argparse import ArgumentParser, HelpFormatter, _SubParsersAction
class NoSubparsersMetavarFormatter(HelpFormatter):
def _format_action(self, action):
result = super()._format_action(action)
if isinstance(action, _SubParsersAction):
# fix indentation on first line
return "%*s%s" % (self._current_indent, "", result.lstrip())
return result
def _format_action_invocation(self, action):
if isinstance(action, _SubParsersAction):
# remove metavar and help line
return ""
return super()._format_action_invocation(action)
def _iter_indented_subactions(self, action):
if isinstance(action, _SubParsersAction):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
# remove indentation
yield from get_subactions()
else:
yield from super()._iter_indented_subactions(action)
parser = ArgumentParser(formatter_class=NoSubparsersMetavarFormatter)
subparsers = parser.add_subparsers(title="Commands")
foo = subparsers.add_parser("foo", help="- foo does foo")
bar = subparsers.add_parser("bar", help="- bar does bar")
parser.parse_args(['-h'])
python 2版本,用python2.7测试
from argparse import ArgumentParser, HelpFormatter, _SubParsersAction
class NoSubparsersMetavarFormatter(HelpFormatter):
def _format_action(self, action):
result = super(NoSubparsersMetavarFormatter,
self)._format_action(action)
if isinstance(action, _SubParsersAction):
return "%*s%s" % (self._current_indent, "", result.lstrip())
return result
def _format_action_invocation(self, action):
if isinstance(action, _SubParsersAction):
return ""
return super(NoSubparsersMetavarFormatter,
self)._format_action_invocation(action)
def _iter_indented_subactions(self, action):
if isinstance(action, _SubParsersAction):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
for subaction in get_subactions():
yield subaction
else:
for subaction in super(NoSubparsersMetavarFormatter,
self)._iter_indented_subactions(action):
yield subaction
parser = ArgumentParser(formatter_class=NoSubparsersMetavarFormatter)
subparsers = parser.add_subparsers(title="Commands")
foo = subparsers.add_parser("foo", help="- foo does foo")
bar = subparsers.add_parser("bar", help="- bar does bar")
parser.parse_args(['-h'])
样本输出:
usage: a.py [-h] {foo,bar} ...
optional arguments:
-h, --help show this help message and exit
Commands:
foo - foo does foo
bar - bar does bar