Skip to main content
 首页 » 编程设计

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

2025年02月15日7unruledboy

我正在使用 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