I want Python argparse to throw an exception rather than usage

前端 未结 2 1550
清酒与你
清酒与你 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:12

    in my case, argparse prints 'too few arguments' then quit. after reading the argparse code, I found it simply calls sys.exit() after printing some message. as sys.exit() does nothing but throws a SystemExit exception, you can just capture this exception.

    so try this to see if it works for you.

        try:
            args = parser.parse_args(args)
        except SystemExit:
            .... your handler here ...
            return
    

提交回复
热议问题