2013-02-25 68 views
1

我正在尋找一種優雅的方式來摺疊 argparse中用於布爾切換的幫助消息。例如這樣的:使用argparse摺疊多個選項

import argparse 

parser = argparse.ArgumentParser("booleans") 

parser.add_argument('--no-store', action='store_false', 
        help="Don't do it'") 
parser.add_argument('--store', action='store_true', 
        help="Do it") 

parser.print_help() 

打印:

usage: booleans [-h] [--no-store] [--store] 

optional arguments: 
    -h, --help  show this help message and exit 
    --no-store  Don't do it' 
    --store   Do it 

但我有一大堆布爾標誌的,我真正喜歡的是能夠把它寫的方式,使它打印:

usage: booleans [-h] [--[no-]store] 

optional arguments: 
    -h, --help  show this help message and exit 
    --[no-]store Do or don't do it. 

有什麼好方法讓我崩潰的論點,並提供自定義幫助 文字和選項的名字呢?

+1

只有帶有布爾參數的'--store'選項可能會更容易。 – 2013-02-25 17:19:13

+0

@larsmans在某些方面會更容易,儘管我實際上知道如何去做。我寧願這樣做,但是,如果任何人都能想出辦法。 – quodlibetor 2013-02-25 17:22:57

+0

這樣''--store --no-store'將是有效的輸入。 – 2013-02-25 17:25:28

回答

1

您可以指定usage參數到ArgumentParser並編寫自己的語法行。

1
usage = ['booleans [-h]'] 
parser = argparse.ArgumentParser("booleans",usage=usage[0], 
    formatter_class=argparse.RawDescriptionHelpFormatter) 

grp1 = parser.add_argument_group(title='Boolean arguments',description='') 
def foo(group, name, help): 
    # create a pair of arguments, with one 'help' line 
    group.add_argument('--no-'+name, action='store_false', help=argparse.SUPPRESS) 
    group.add_argument('--'+name, action='store_true', help=argparse.SUPPRESS) 
    usage.append(' [--[no-]%s]'%name) 
    group.description += "[--[no-]%s]\t%s.\n"%(name,help) 
foo(grp1, 'store', "Do or don't do it",) 
foo(grp1, 'remove', "Do or don't do it",) 
parser.usage = ''.join(usage) 
parser.print_help() 

產生

usage: booleans [-h] [--[no-]store] [--[no-]remove] 

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

Boolean arguments: 
    [--[no-]store] Do or don't do it. 
    [--[no-]remove] Do or don't do it. 

我用RawDescriptionHelpFormatter允許使用的\t。它也會允許多行描述(其他對參數)。

與​​真正無關緊要的參數是在grp1parser