2017-09-16 87 views
2

我使用argparse接受选项,其中之一是一个列表看起来很好:蟒蛇argparse使用带有NARGS列表选项显示炒帮助信息

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

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

谢谢。

+0

你的代码有一个错字(缺失报价) –

+0

你真的需要'NARGS = '*''?是否允许多个或零主机名? –

+0

@ Jean-FrançoisFabre - 你是对的,我已经修复了,但是错字只是在问题中,而不是在运行的代码中。 – deez

回答

1

*格式化固定为嵌套[]。它应该表达的意思是零,一个或多个字符串被接受。它同时影响使用情况和帮助热线。 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 ...]] 

的帮助下完成suupression:

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

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

总是有来继承帮助格式化选项,并改变一种或两种方法。

使用该metavar的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