2017-09-16 24 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