Argparse
会显示有关选项列表的消息,就像这个例子中一样:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--styles', choices=long_list_of_styles)
当我传递一个很长的列表时,帮助信息看起来不太好,实际上它看起来很混乱,并且由于打印了所有选项,掩盖了其他参数的存在。
有没有办法告诉Argparser
不要打印参数选项?
Argparse
会显示有关选项列表的消息,就像这个例子中一样:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--styles', choices=long_list_of_styles)
当我传递一个很长的列表时,帮助信息看起来不太好,实际上它看起来很混乱,并且由于打印了所有选项,掩盖了其他参数的存在。
有没有办法告诉Argparser
不要打印参数选项?
建议的重复问题,Python 的 argparse 选项受限制的打印 提出了一个相对复杂的解决方案 - 自定义 HelpFormatter
或自定义 type
。
更高票的问题/答案是 Python argparse:大量选项导致丑陋的帮助输出
您可以通过使用 [argparse] choices
进行搜索来找到更多信息。
最简单的解决方案是设置 metavar
参数。 None
在 choices
插槽中不显示任何内容,但您可能需要一个简短的单词。
In [8]: styles=['one','two','three','four']
In [10]: parser = argparse.ArgumentParser()
In [11]: parser.add_argument('--styles', metavar='STYLE', choices=styles,
...: help='list of choices: {%(choices)s}')
Out[11]: _StoreAction(option_strings=['--styles'], dest='styles', nargs=None, const=None, default=None, type=None, choices=['one', 'two', 'three', 'four'], help='list of choices: {%(choices)s}', metavar='STYLE')
In [12]: parser.print_help()
usage: ipython3 [-h] [--styles STYLE]
optional arguments:
-h, --help show this help message and exit
--styles STYLE list of choices: {one, two, three, four}
我在帮助文档中包含了 %(choices)s
,以便在那里列出它们。当然,您也可以在那里放置自己的摘要。长列表比在usage
中更适合放在那里。
choices
,而是手动检查给定的选项是否为选择。提供一个像--help-styles
这样的选项,它将打印可用样式名称的列表,以便用户仍然可以访问支持的选择列表。 - Bakuriu