Python argparse conditional requirements

后端 未结 2 653
迷失自我
迷失自我 2021-02-18 23:47

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         


        
2条回答
  •  粉色の甜心
    2021-02-19 00:50

    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)
    

提交回复
热议问题