I have a Python program that maintains a list of contacts and I want it to support following options through the command line:
- --show , takes a string argument
- --list , takes no argument
- --add , takes a string argument
- --number , takes an int argument
- --email , takes a string argument
What I need is:
prog [--show xyz | --list | --add xyz --number 123 --email [email protected] ]
I tried to implement it using subparsers as follows:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparser1 = subparsers.add_parser('1')
subparser1.add_argument('--show', type=str, help="Shows the contact based on the given name provided as argument")
subparser1.add_argument('--list', action='store_true', help= "Prints all the contacts")
subparser2 = subparsers.add_parser('2')
subparser2.add_argument('--add', type=str, help="Adds a new contact by this name",required=True)
subparser2.add_argument('--number', type=int, help="The Phone Number for the new contact",required=True)
subparser2.add_argument('--email', type=str, help="Email address for the new contact",required=True)
The problem is that I don't to want to provide the number/name of the subparser I wanna use through the command-line.
E.g:
prog.py 1 --list
prog.py 2 --add xyz --number 1234 --email [email protected]
I tried to make it work with mutually_exclusive_group but couldn't. Is there a way around this usage?
--on the commandsshow,list, andadd