argparse arguments nesting

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')

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

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

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

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

Thanks, Arshavski Alexander.


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 add name --web_port=XXXX
python upgrade name

Something like:

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

add_p = subparsers.add_parser('add')

upg_p = subparsers.add_parser('upgrade')

If you try run upgrade name --web_port=1234

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

Likewise, if you try 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.

Need Your Help

How to find out where alias (in the bash sense) is defined when running Terminal in Mac OS X

terminal alias bash

How can I find out where an alias is defined on my system? I am referring to the kind of alias that is used within a Terminal session launched from Mac OS X (10.6.3).

Devise and Rails - ArgumentError in Devise::RegistrationsController#create

ruby-on-rails ruby ruby-on-rails-3 devise

When a new user submits a new user registration form they get the below error message. I suspect it because the devise/registrations_controller.rb doesn't exist.