Reputation: 5391
I have a following code in python:
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')
group.add_argument('-r', '--remove', dest='name_to_remove', help='Remove a group')
group.add_argument('-l', '--list', dest="list_server_or_group_name", help='Get group or server state/configuration')
My problem is with "-l" option. I want to be able to list a specific group and to list all the groups. Currently I do it with:
"python my_script.py -l group_name" - for listing a specific group and "python my_script.py -l all" - for listing all the groups.
But I would like to list all the groups just with: "python my_script.py -l". How should I change my code in order to be able to run it this way? and how can I check it later in code?
Thanks, Arshavski Alexander.
Upvotes: 2
Views: 1011
Reputation: 157504
This isn't possible with optparse
.
However, if you switch from optparse
to argparse
(since 2.7 or 3.2) you can pass nargs='?'
:
'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.
group.add_argument('-l', '--list', dest="list_server_or_group_name",
help='Get group or server state/configuration',
nargs='?', default=None, const='all')
Upvotes: 4