Skip to content
Advertisement

Python argparse conditional requirements

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 required

For example,

-2 [good]
-3 a -4 b [good]
-3 a [not good, -4 required]
-2 -5 c [good]
-2 -3 a [good]

There are a number of similar questions here, but either they don’t address this situation or I don’t understand.

Python 2.7 if that matters.

Advertisement

Answer

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 <a> *and* -4 <b> 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 <a> *and* -4 <b> are required
2
$ 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement