python argparse - 使用带有 nargs 的列表选项显示困惑的帮助消息

标签 python argparse

我正在使用 argparse 接受选项,其中一个是列表:

parser.add_argument('-S', '--size', help='Number of results to show', default=1000, dest='size', metavar='')
parser.add_argument('-H','--hostname', nargs='*', help='Hostname list', dest='hostname', metavar='')

当我使用 nargs 选项时,帮助信息看起来不太好:

optional arguments:
  -h, --help            show this help message and exit
  -S , --size           Number of results to show
  -H [ [ ...]], --hostname [ [ ...]]
                        Hostname list

如何使主机名看起来像其他参数? metavar='' 技巧在这里不起作用。

谢谢。

最佳答案

* 格式固定为嵌套的 []。它应该传达接受零个、一个或多个字符串的意思。它还会影响使用和帮助热线。 Metavar 允许一些控制,但不能完全替换。

In [461]: p=argparse.ArgumentParser()
In [462]: a=p.add_argument('-f','--foo',nargs='*')
In [463]: p.print_help()
usage: ipython3 [-h] [-f [FOO [FOO ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -f [FOO [FOO ...]], --foo [FOO [FOO ...]]

一个字符串:

In [464]: a.metavar = 'F'
In [465]: p.print_help()
usage: ipython3 [-h] [-f [F [F ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -f [F [F ...]], --foo [F [F ...]]

一个元组:

In [467]: a.metavar = ('A','B')
In [468]: p.print_help()
usage: ipython3 [-h] [-f [A [B ...]]]

optional arguments:
  -h, --help            show this help message and exit
  -f [A [B ...]], --foo [A [B ...]]

完全抑制帮助:

In [469]: a.help = argparse.SUPPRESS
In [470]: p.print_help()
usage: ipython3 [-h]

optional arguments:
  -h, --help  show this help message and exit

始终可以选择对帮助格式化程序进行子类化,并更改一两个方法。

使用元变量的 HelpFormatter 方法:

def _format_args(self, action, default_metavar):
    get_metavar = self._metavar_formatter(action, default_metavar)
    if action.nargs is None:
        result = '%s' % get_metavar(1)
    elif action.nargs == OPTIONAL:
        result = '[%s]' % get_metavar(1)
    elif action.nargs == ZERO_OR_MORE:
        result = '[%s [%s ...]]' % get_metavar(2)
    elif action.nargs == ONE_OR_MORE:
        result = '%s [%s ...]' % get_metavar(2)
    elif action.nargs == REMAINDER:
        result = '...'
    elif action.nargs == PARSER:
        result = '%s ...' % get_metavar(1)
    else:
        formats = ['%s' for _ in range(action.nargs)]
        result = ' '.join(formats) % get_metavar(action.nargs)
    return result

关于python argparse - 使用带有 nargs 的列表选项显示困惑的帮助消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46256416/

相关文章:

python - pygame.Surface 和鼠标之间的碰撞检测不起作用

python - 使用 argparse 将参数发送到 Python 脚本中的函数

python - 有没有办法在 Argparse 中设置没有任何前缀的选项?

Vim 的 Python 和 Django 插件

python - 赠品命令时间转换错误 Discord.Py

python - 为乌鸦添加自定义标签

python-3.x - argparse - 不带前缀的可选参数

python - 是否可以使用 argparse (Python) 在另一个组内创建一个互斥组?

python - 已指定检测参数(argparse)

python - 安卓工作室 : IncorrectOperationException when 'Add as Library' is clicked whilst trying to configure Google Apps Endpoints client libraries