How do I set up argparse as follows:
if -2 is on the command line, no other arguments are required
if -2 is not on the command line, -3 and -4 arguments are requ
A subparser (as suggested in comments) might work.
Another alternative (since mutually_exclusive_group
can't quite do this) is just to code it manually, as it were:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-2', dest='two', action='store_true')
parser.add_argument('-3', dest='three')
parser.add_argument('-4', dest='four')
parser.add_argument('-5', dest='five')
args = parser.parse_args()
if not args.two:
if args.three is None or args.four is None:
parser.error('without -2, *both* -3 *and* -4 are required')
print args
return 0
Adding a little driver to this:
import sys
sys.exit(main())
and run with your examples, it seems to do the right thing; here are two runs:
$ python mxgroup.py -2; echo $?
Namespace(five=None, four=None, three=None, two=True)
0
$ python mxgroup.py -3 a; echo $?
usage: mxgroup.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
mxgroup.py: error: without -2, *both* -3 *and* -4 are required
2
$