I have a Python program that maintains a list of contacts and I want it to support following options through the command line:
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?
Do you really need the double dash (--
) before your command?
If not, you could do:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command')
show_subparser = subparsers.add_parser('show')
show_subparser.add_argument('name', type=str)
list_subparser = subparsers.add_parser('list')
add_subparser = subparsers.add_parser('add')
add_subparser.add_argument('phone', type=int)
args = parser.parse_args()
# Do something with your args
print args
This would limit you to the above defined arguments.
Inasmuch you can do either prog show xyz
or prog add 123
but you can't do prog show xzy add 123
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With