82

私のスクリプトは、1 つのメイン パーサーと複数のサブパーサーを定義します。-pこの引数をいくつかのサブパーサーに適用したいと考えています。これまでのところ、コードは次のようになります。

parser = argparse.ArgumentParser(prog="myProg")
subparsers = parser.add_subparsers(title="actions")

parser.add_argument("-v", "--verbose",
                    action="store_true",
                    dest="VERBOSE",
                    help="run in verbose mode")

parser_create = subparsers.add_parser ("create", 
                                        help = "create the orbix environment")
parser_create.add_argument ("-p", 
                            type = int, 
                            required = True, 
                            help = "set db parameter")

# Update
parser_update = subparsers.add_parser ("update", 
                                        help = "update the orbix environment")
parser_update.add_argument ("-p", 
                            type = int, 
                            required = True, 
                            help = "set db parameter")

ご覧のとおり、add_arument ("-p")が 2 回繰り返されます。私は実際にはもっと多くのサブパーサーを持っています。繰り返しを避けるために、既存のサブパーサーをループする方法はありますか?

記録のために、私はPython 2.7を使用しています

4

4 に答える 4

94

これは、共通のオプションを含む親パーサーを定義することで実現できます。

import argparse

parent_parser = argparse.ArgumentParser(description="The parent parser")
parent_parser.add_argument("-p", type=int, required=True,
                           help="set db parameter")
subparsers = parent_parser.add_subparsers(title="actions")
parser_create = subparsers.add_parser("create", parents=[parent_parser],
                                      add_help=False,
                                      description="The create parser",
                                      help="create the orbix environment")
parser_create.add_argument("--name", help="name of the environment")
parser_update = subparsers.add_parser("update", parents=[parent_parser],
                                      add_help=False,
                                      description="The update parser",
                                      help="update the orbix environment")

これにより、次の形式のヘルプメッセージが生成されます。

parent_parser.print_help()

出力:

usage: main.py [-h] -p P {create,update} ...
The parent parser
optional arguments:
  -h, --help       show this help message and exit
  -p P             set db parameter
actions:
  {create,update}
    create         create the orbix environment
    update         update the orbix environment
parser_create.print_help()

出力:

usage: main.py create [-h] -p P [--name NAME] {create,update} ...
The create parser
optional arguments:
  -h, --help       show this help message and exit
  -p P             set db parameter
  --name NAME      name of the environment
actions:
  {create,update}
    create         create the orbix environment
    update         update the orbix environment

createただし、プログラムを実行する場合、アクション(または)を指定しなくてもエラーは発生しませんupdate。この動作が必要な場合は、次のようにコードを変更してください。

<...>
subparsers = parent_parser.add_subparsers(title="actions")
subparsers.required = True
subparsers.dest = 'command'
<...>

この修正は、プルリクエストの追跡の問題を参照するこのSOの質問で取り上げられました。

@hpauljによる更新

2011年以降、サブパーサーの処理が変更されたため、メインパーサーをとして使用することはお勧めできませんparentdestより一般的には、メインパーサーとサブパーサーの両方で同じ引数(同じ)を定義しようとしないでください。サブパーサーの値は、メインによって設定されたものをすべて上書きします(サブパーサーでdefaultもこれを行います)。として使用する個別のパーサーを作成しますparents。また、ドキュメントに示されているように、親はを使用する必要がありますadd_help=False

于 2011-09-21T11:19:20.217 に答える
15

サブパーサーをループして、それらすべてに同じオプションを追加することもできます。

parser = argparse.ArgumentParser(prog="myProg")
subparsers = parser.add_subparsers(title="actions")
parser.add_argument("-v", "--verbose",
                    action="store_true",
                    dest="VERBOSE",
                    help="run in verbose mode")

parser_create = subparsers.add_parser ("create", 
                                        help = "create the orbix environment")
parser_update = subparsers.add_parser ("update", 
                                        help = "update the orbix environment")

for subparser in [parser_create, parser_update]:
    subparser.add_argument ("-p", 
                            type = int, 
                            required = True, 
                            help = "set db parameter")
于 2015-08-26T09:40:19.050 に答える