【问题标题】:Disable argparse choices message禁用 argparse 选择消息
【发布时间】:2016-07-18 00:21:20
【问题描述】:

Argparse 显示有关选项列表的消息,如下例所示:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--styles', choices=long_list_of_styles)

当我传递一个很长的列表时,帮助消息看起来不太好,实际上它看起来很混乱,而且它的存在掩盖了其他参数,因为所有这些选择都被打印出来了。

有没有办法告诉Argparser 不要打印参数选择?

【问题讨论】:

  • 这已经被问过了。您必须使用链接问题中所示的自定义帮助格式化程序。
  • 谢谢,我在 Google 上没有得到任何结果。但是,链接答案中的两种解决方案都太复杂了。我将删除选择。
  • 我的建议:不要使用choices 并手动检查给出的选项是否是一个选项。提供像 --help-styles 这样的选项,它将打印可用样式的名称列表,以便用户仍然可以访问支持的选项列表。

标签: python python-3.x argparse


【解决方案1】:

建议的副本,Python's argparse choices constrained printing 提出了一个相对复杂的解决方案——自定义HelpFormatter。或者自定义type

投票较高的问题/答案是Python argparse: Lots of choices results in ugly help output

您可以通过[argparse] choices 搜索找到更多信息。

最简单的解决方案是设置metavar 参数。 Nonechoices 槽中不显示任何内容,但您可能想要一个简短的单词

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 更适合。

【讨论】:

  • 鉴于您在另一个副本上找到了此答案,您应该重新打开问题并将其作为另一个问题的副本关闭,而不是再次重新复制。 ..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2016-10-04
  • 2021-10-29
  • 2013-12-02
  • 2012-08-17
  • 2016-01-11
  • 2013-04-28
相关资源
最近更新 更多