argparse 参数嵌套 [英] argparse arguments nesting

查看:32
本文介绍了argparse 参数嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有以下代码:

I have a following code in python:

parser = argparse.ArgumentParser(description='Deployment tool')
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', dest='name_to_add', help='Add a new group or a role to existing group')
group.add_argument('-u', '--upgrade', dest='name_to_upgrade', help='Upgrade a group with the new version')
parser.add_argument('--web_port', help='Port of the WEB instance that is being added to the group')

我的问题是--web_port"选项.我希望只能使用-a"选项而不是-u"添加此选项.

My problem is with "--web_port" option. I want to be able to add this option only with "-a" option but not with "-u".

希望能够运行:python my_script.py -a name --web_port=XXXX".

I want to be able to run: "python my_script.py -a name --web_port=XXXX".

不想能够运行:python my_script.py -u name --web_port=XXXX"

I don't want to be able to run: "python my_script.py -u name --web_port=XXXX"

我应该如何更改我的代码才能以这种方式运行它?

How should I change my code in order to be able to run it this way?

谢谢,阿尔沙夫斯基亚历山大.

Thanks, Arshavski Alexander.

推荐答案

与其让 -a-u 成为选项,不如让它们成为子命令.然后,使 --web-port 成为 add 子命令的一个选项:

Instead of having -a and -u be options, you may want to make them subcommands. Then, make --web-port an option of the add subcommand:

python my_script.py add name --web_port=XXXX
python my_script.py upgrade name

类似于:

parser = argparse.ArgumentParser(description='Deployment tool')
subparsers = parser.add_subparsers()

add_p = subparsers.add_parser('add')
add_p.add_argument("name")
add_p.add_argument("--web_port")
...

upg_p = subparsers.add_parser('upgrade')
upg_p.add_argument("name")
...

如果你尝试运行

my_script.py upgrade name --web_port=1234

您将收到无法识别的参数--web_port"的错误.

you'll get an error for unrecognized argument "--web_port".

同样,如果你尝试

my_script.py add name upgrade

由于无法识别的参数升级",您将收到错误消息,因为您只为add"子命令定义了一个位置参数.

you'll get an error for unrecognized argument "upgrade", since you only defined a single positional argument for the 'add' subcommand.

换句话说,子命令是隐式互斥的.唯一的微小的疣是您需要为每个添加名称"位置参数子解析器.

In other words, subcommands are implicitly mutually exclusive. The only tiny wart is that you need to add the "name" positional parameter to each subparser.

这篇关于argparse 参数嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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