Python argparse-向多个子解析器添加参数 [英] Python argparse - Add argument to multiple subparsers

查看:52
本文介绍了Python argparse-向多个子解析器添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本定义了一个主解析器和多个子解析器.我想将-p参数应用于某些子解析器.到目前为止,代码如下所示:

My script defines one main parser and multiple subparsers. I want to apply the -p argument to some subparsers. So far the code looks like this:

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")重复了两次.实际上,我有更多的次级解析器.有没有一种方法可以遍历现有的子解析器以避免重复?

As you can see the add_arument ("-p") is repeated twice. I actually have a lot more subparsers. Is there a way to loop through the existing subparsers in order to avoid repetition?

出于记录,我使用的是Python 2.7

For the record, I am using Python 2.7

推荐答案

这可以通过定义

这会产生以下格式的帮助消息:

This produces help messages of the format:

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

但是,如果您运行程序,则如果未指定操作(即createupdate),则不会遇到错误.如果您希望这种行为,请按如下所示修改您的代码.

However, if you run your program, you will not encounter an error if you do not specify an action (i.e. create or update). If you desire this behavior, modify your code as follows.

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

此修复程序出现在此SO问题中,该问题指的是跟踪拉动的问题请求.

This fix was brought up in this SO question which refers to an issue tracking a pull request.

这篇关于Python argparse-向多个子解析器添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆