2

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.

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the fast response. For some reason it doesn't work for me. After adding this and running with "-l" option, args.list_server_or_group_name is None for some reason and I expect it to be "all"
@alexarsh -- Try adding the const keyword (e.g. const = 'all') as well. Most enlighteningly, try a simple program where you add an argument as: grp.add_argument('-l',nargs='?',default=None,const='foo') and then walk through the different options (calling with -l, -l foo and without -l).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.