问题描述: 在Python类中使用argparse进行命令行参数解析时,需要进行参数合法性的验证。但是在类中使用argparse进行参数验证时,会存在无法正常抛出错误信息的问题,使得调试变得困难。
通过重写ArgumentParser的error方法,将错误信息通过raise语句抛出,从而解决参数验证时无法正常抛出错误信息的问题。
代码示例:
import argparse
class MyArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ValueError(message)
class MyClass():
def __init__(self):
self.parser = MyArgumentParser(description='MyClass Description')
self.parser.add_argument('--age', type=int, help='Age of the person')
self.parser.add_argument('--name', type=str, help='Name of the person')
def parse(self, args):
return self.parser.parse_args(args)
if __name__ == '__main__':
obj = MyClass()
try:
args = obj.parse(['--age', 'abc'])
except ValueError as e:
print(e)