Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument Parser Python conditional requirement

I have a Python program that maintains a list of contacts and I want it to support following options through the command line:

  1. --show , takes a string argument
  2. --list , takes no argument
  3. --add , takes a string argument
  4. --number , takes an int argument
  5. --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?

like image 639
Adnan Avatar asked Jan 01 '23 20:01

Adnan


1 Answers

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.

like image 80
Léopold Houdin Avatar answered Jan 11 '23 04:01

Léopold Houdin