1

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.

引数を折りたたんで、カスタム ヘルプ テキストとオプション名を提供する良い方法はありますか?

4

2 に答える 2

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ます。また、複数行の説明 (他の引数のペア) も許可されます。

の場合、引数が inかSUPPRESSかは問題ではありません。grp1parser

于 2014-04-10T20:50:44.593 に答える