Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I constrain my python script to only accepting one argument? (argparse)

I would like a script that has (for example) three arguments:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--a",help="Argument a")
parser.add_argument("--b",help="Argument b")
parser.add_argument("--c",help="Argument c")
args= parser.parse_args()

But make it so that it is only possible to specify only either 'a','b', or 'c' at any give time e.g. you can specify 'a' but not 'b' or 'c' Is this possible and how would I achieve it?

like image 853
Sheldon Avatar asked Nov 09 '12 14:11

Sheldon


2 Answers

argpase lets you specify this using the add_mutually_exclusive_group() method.

import argparse
parser = argparse.ArgumentParser()
g = parser.add_mutually_exclusive_group()
g.add_argument("--a",help="Argument a")
g.add_argument("--b",help="Argument b")
g.add_argument("--c",help="Argument c")
args= parser.parse_args()
like image 98
bgporter Avatar answered Oct 25 '22 13:10

bgporter


Use the add_mutually_exclusive_group() mentioned above to check this on the argparse level already.

If you like to have more control about error message and the like, you can of course check the results later:

if len([x for x in args.a, args.b, args.c if x is not None]) > 1:
  raise Exception("Not allowed!")
like image 25
Alfe Avatar answered Oct 25 '22 13:10

Alfe