Python argparse conditional requirements

吃可爱长大的小学妹 提交于 2019-12-03 23:32:08

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
$ 

I think it is pretty hard to achieve that (including a nice help message) while only using the standard argparse functions. You can however easily test it yourself after parsing the arguments. You can describe the extra requirements in the epilogue or so. Note that it is unusual to use numbers as options, I had to use dest='two', since args.2 is not valid syntax.

#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser(
   description='bla bla',
   epilog='Note: arguments -3 and -4 are required when -2 is missing')

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 and (args.three is None or args.four is None):
    parser.error('arguments -3 and -4 are required when -2 is missing')

print 'Good:', args

With these results:

[~]: ./test.py -h
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]

bla bla

optional arguments:
  -h, --help  show this help message and exit
  -2
  -3 THREE
  -4 FOUR
  -5 FIVE

Note: arguments -3 and -4 are required when -2 is missing

[~]: ./test.py -2
Good: Namespace(five=None, four=None, three=None, two=True)
[~]: ./test.py -3 a -4 b
Good: Namespace(five=None, four='b', three='a', two=False)
[~]: ./test.py -3 a
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
test.py: error: arguments -3 and -4 are required when -2 is missing
[~]: ./test.py -2 -5 c
Good: Namespace(five='c', four=None, three=None, two=True)
[~]: ./test.py -2 -3 a
Good: Namespace(five=None, four=None, three='a', two=True)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!