argparse arguments nesting

≡放荡痞女 提交于 2019-12-04 23:56:27
chepner

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

Something like:

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")
...

If you try run

my_script.py upgrade name --web_port=1234

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

Likewise, if you try

my_script.py add name upgrade

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!