跳水後真正深入到argparse源代碼,我構建了一個破解去除多餘{cmd1,...}
選擇列表。
該破解實現了一個自定義幫助格式化程序,它在處理 子分析程序操作時修改了HelpFormatter
的格式化方法。具體而言,它會刪除子命令參數組中的子分析器metavar
和 help
行,並刪除這些子命令的額外縮進 。
請小心使用。
蛇皮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'])
蛇皮版本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
完美,恰好我需要什麼!謝謝。 –
仍然不可能完全刪除該標頭。 'argparse'離開空行。 –
@anatolytechtonik看到我下面的破解。 – Naitree