Reputation: 396
I am writing a script that can do multiple things, depending on the arguments passed into the command line. For example:
#changed and simplified from actual code
parser.add_argument('-a','--apple')
parser.add_argument('-b','--boy')
parser.add_argument('-c', '--car')
parser.add_argument('-d', '--dog')
args = parser.parse_args()
I only want 1 argument in the commandline. So, only one of -a,-b,-c,-d
would be accepted, and then the code will execute based on whichever argument was passed.
I can do this by a series of if statements, like
if args.a:
if args.b:
etc. Is there a better way to approach this?
For each command line option (-a,-b,-c,-d
), I would like to have some arguments passed in. These arguments would be specific and would vary depending on the initial command line option. For example:
python test.py -a apple aardvark aquaman
I considered using nargs
, but I was not sure how to make each argument was
a
.How could I approach this?
Upvotes: 0
Views: 231
Reputation: 102039
You can define mutually exclusive options using add_mutually_exclusive_group()
:
group = parser.add_mutually_exclusive_group()
group.add_argument('-a','--apple')
group.add_argument('-b','--boy')
group.add_argument('-c', '--car')
group.add_argument('-d', '--dog')
args = parser.parse_args()
Regarding the second part you can specify nargs
and a custom type
. The type
can simply be a function that takes the string of the argument:
def check_a(val):
if not val or not val[0] == 'a':
raise argparse.ArgumentTypeError('Must be a value starting with a')
return val
parser.add_argument('-a', '--apple', nargs=3, type=check_a)
Regarding the order of the arguments passed to option apple
AFAIK you have to check it afterswards:
args = parser.parse_args()
if is_wrong_order(args.apple):
parser.error('Incorrect argument order to apple')
Anyway in your case you probably want to use subparsers instead of options.
Upvotes: 1