Using 'argparse.ArgumentError' in Python

前端 未结 2 1964
心在旅途
心在旅途 2020-12-24 10:55

I\'d like to use the ArgumentError exception in the argparse module in Python, but I can\'t figure out how to use it. The signature says that it sh

2条回答
  •  生来不讨喜
    2020-12-24 11:25

    While parser.error() is what most people probably want, it is also possible to use argparse.ArgumentError() (as the question asks.) You need a reference to the argument, like the bar_arg in the example below:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo')
    bar_arg = parser.add_argument('--bar')
    
    args = parser.parse_args()
    if args.bar == 'xyzzy':
        raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")
    
    if args.foo == 'xyzzy':
        parser.error("Can't be 'xyzzy'")
    

    This will result in output like the one below:

    $ python argparse_test.py --foo xyzzy
    usage: argparse_test.py [-h] [--foo FOO] [--bar BAR]
    argparse_test.py: error: Can't be 'xyzzy'
    
    $ python argparse_test.py --bar xyzzy
    Traceback (most recent call last):
      File "argparse_test.py", line 10, in 
        raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")
    argparse.ArgumentError: argument --bar: Can't be 'xyzzy'
    

提交回复
热议问题