Reputation: 5413
Hi All i am working on creation of help menu in python .Below is the code.
__author__ = 'akthakur'
import argparse
import database_helper
import sys
import database_operations_full
import withoutTransactionaldata
print("Database Backup and restoration Application".center(60,'*'))
parser = argparse.ArgumentParser(description="My database backup application")
group = parser.add_mutually_exclusive_group()
group.add_argument("-g","--group",type=str,help="defines database groups",default='nothing')
group.add_argument("-a","--all",help="backup all databases",action="store_true")
group.add_argument("-d","--databases",nargs='+',help="take multiple databases as input",default=[])
parser.add_argument("-r","--reference",help="backups reference data-only",action="store_true")
suppose name of python file to which i have written above code is test.py so following operation should throw error
python test.py -r
i don't anyone to call my application with -r option alone .If one has to use -r then he must also have to use -a or -d or -g
Upvotes: 1
Views: 111
Reputation: 2320
import argparse, sys
def db_prog(*args):
""" stub code """
print sys.argv[1:]
parser = argparse.ArgumentParser(description="myD")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-g")
group.add_argument("-a")
group.add_argument("-d")
parser.add_argument("-r", help="additionally must use one of -g, -a, -d")
args = parser.parse_args()
db_prog(sys.argv)
Run 1
$ python argtest.py -a A
['-a', 'A']
Run 2
$ python argtest.py -r R
usage: argtest.py [-h] (-g G | -a A | -d D) [-r R]
argtest.py: error: one of the arguments -g -a -d is required
Run 3
$ python argtest.py -r R -g G
['-r', 'R', '-g', 'G']
Run 4
$ python argtest.py -a A -g F -d D
usage: argtest.py [-h] (-g G | -a A | -d D) [-r R]
argtest.py: error: argument -g: not allowed with argument -a
Upvotes: 0
Reputation: 12728
I do not see such a function in the argparse module, but when you create shell commands, it is good practice to have some defaults, so that you seldom encounter the error "option XYZ is missing".
So, I guess, that is something that is not covered by argparse and must be handled by you, if you want it.
Alternatively, if possible, I would assume a default value for -g,-a,-d -- and when neither is set use that. Of course in this case, you also have to do some processing, because all your options are set to false.
Upvotes: 0
Reputation: 1135
if they always have to specify one of -a , -d, -g then use add_mutually_exclusive_group(required=True)
if they only need to do that when they specify -r, you'll need an if statement like:
args = parser.parse_args()
if args.reference:
if not args.databases and not args.all and args.group == 'nothing':
parser.error("Must specify -a, -d, or -g with -r")
Upvotes: 2