Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable an argument if another is present?

In my script argparse there are some arguments that will conflict if another argument of opposite kind is passed. I want to disable the --arg2 if --arg1 is already present. Currently I haven't found any way to do so.

like image 824
Santosh Kumar Avatar asked Jul 23 '13 08:07

Santosh Kumar


1 Answers

Use a mutually exclusive group:

parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group()
group.add_argument('--arg1')
group.add_argument('--arg2')

Only one argument in the group is allowed to be used.

Demo:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--arg1')
_StoreAction(option_strings=['--arg1'], dest='arg1', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> group.add_argument('--arg2')
_StoreAction(option_strings=['--arg2'], dest='arg2', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args(['--arg1', 'foo'])
Namespace(arg1='foo', arg2=None)
>>> parser.parse_args(['--arg2', 'bar'])
Namespace(arg1=None, arg2='bar')
>>> parser.parse_args(['--arg1', 'foo', '--arg2', 'bar'])
usage: PROG [-h] [--arg1 ARG1 | --arg2 ARG2]
PROG: error: argument --arg2: not allowed with argument --arg1
like image 88
Martijn Pieters Avatar answered Oct 22 '22 07:10

Martijn Pieters