I want Python argparse to throw an exception rather than usage

前端 未结 2 1549
清酒与你
清酒与你 2020-12-13 13:08

I don\'t think this is possible, but I want to handle exceptions from argparse myself.

For example:

import argparse
parser = argparse.ArgumentParser(         


        
2条回答
  •  一整个雨季
    2020-12-13 13:20

    You can subclass ArgumentParser and override the error method to do something different when an error occurs:

    class ArgumentParserError(Exception): pass
    
    class ThrowingArgumentParser(argparse.ArgumentParser):
        def error(self, message):
            raise ArgumentParserError(message)
    
    parser = ThrowingArgumentParser()
    parser.add_argument(...)
    ...
    

提交回复
热议问题