ved*_*dar 3 python argparse python-3.x
Argparse 显示有关选项列表的消息,如下例所示:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--styles', choices=long_list_of_styles)
Run Code Online (Sandbox Code Playgroud)
当我传递一个很长的列表时,帮助消息看起来不太好,实际上它看起来很混乱,并且它的存在掩盖了其他参数,因为所有这些选项都被打印出来。
有没有办法告诉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}
Run Code Online (Sandbox Code Playgroud)
我%(choices)s在帮助中列出了它们。你当然可以把你自己的总结放在那里。一个长列表在那里比在usage.
| 归档时间: |
|
| 查看次数: |
977 次 |
| 最近记录: |