[英]Modular help message with python argparse
我正在使用 python argparse 來管理命令行選項。 When the number of options becomes large, the help message (what argparse prints when you pass --help
) is getting intimidating and hard to read, simply because it is to long. 其他程序有時通過模塊化幫助消息來解決這個問題:它們只顯示帶有--help
的“核心選項”,並且具有諸如--help-modulea
、 --help-moduleb
等選項。
我認為 argparse 允許在存在子命令的情況下進行類似的操作,基本上就像 git 所做的那樣: ./script.py command --help
。 然而,我的應用程序沒有子命令之類的東西,只有一大組選項(盡管可以很好地分組)。
有沒有(合理的)方法可以用 argparse 做到這一點?
感謝@hpaulj 的回答,我對argparse
內部進行了適當的了解,並提出了以下建議。 雖然它有一些警告,但我覺得這是一個好的開始:
class ModularHelpEnabler(argparse.Action):
def __call__(self, parser, namespace, values, option_string = None):
parser.enable_modular_help(self.const)
class ModularArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
self._modular_action_groups = {}
modular_help_groups = kwargs.pop('modular_help_groups', [])
super().__init__(*args, **kwargs)
self._modular_help_groups = {}
for name in modular_help_groups:
self._modular_help_groups[name] = self.add_argument_group(name)
def add_argument_group(self, *args, **kwargs):
name = kwargs.pop('help_name', None)
help_group = kwargs.pop('help_group', None)
help_text = kwargs.pop('help_group', 'show help for {}')
grp = super().add_argument_group(*args, **kwargs)
if name is not None:
self._modular_action_groups[grp] = name
parser = self
if help_group is not None:
parser = self._modular_help_groups[help_group]
parser.add_argument('--help-{}'.format(name), action=ModularHelpEnabler, nargs=0, const=grp, help = help_text.format(name))
return grp
def enable_modular_help(self, grp):
del self._modular_action_groups[grp]
def format_help(self):
self._action_groups = [
ag for ag in self._action_groups
if ag not in self._modular_action_groups
]
return super().format_help()
警告(並非易事,AFAIK):
--help-foo
並不意味着--help
。--help-foo
需要在--help
之前給出。 不幸的是, --help
直接觸發打印幫助並退出。 如果我們保留此行為,則需要在--help
本身之前指定修改幫助消息的所有內容。 我們可以推遲打印幫助,直到解析完成,但這意味着--help
不再隱藏解析錯誤(就像現在一樣),顯着改變當前行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.