argparse验证在Python类中的问题
创始人
2024-09-13 06:30:39
0

问题描述: 在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)

相关内容

热门资讯

透视ai!wpk辅助器,aap... 透视ai!wpk辅助器,aapoker透视脚本,透牌教程(原先是真的有挂);原来确实真的有挂(需添加...
透视ai代打!hhpoker辅... 透视ai代打!hhpoker辅助软件下载,hhpoker外挂靠谱吗,2025版教程(一向存在有挂);...
透视数据!aapoker辅助工... 透视数据!aapoker辅助工具存在吗,xpoker辅助工具,力荐教程(起初真的是有挂);(需添加指...
透视透视!hhpoker透视脚... 透视透视!hhpoker透视脚本视频,hhpoker俱乐部是干嘛的,解密教程(原来真的有挂)1、不需...
透视苹果版!wpk透视辅助,w... 透视苹果版!wpk透视辅助,wepoker辅助是真的假的,扑克教程(总是存在有挂)1、玩家可以在wp...
透视透视挂!智星德州辅助译码插... 透视透视挂!智星德州辅助译码插件靠谱吗,智星菠萝可以辅助吗,科技教程(竟然存在有挂)1、让任何用户在...
透视脚本!wepoker透视脚... 透视脚本!wepoker透视脚本安卓,hh poker辅助有用吗,可靠教程(都是是有挂);玩家在we...
透视肯定!wepoker免费透... 透视肯定!wepoker免费透视脚本,aapoker怎么选牌,扑克教程(素来是有挂);wepoker...
透视肯定!德普之星怎么作弊,w... 透视肯定!德普之星怎么作弊,wepoker透视app下载,系统教程(真是是真的有挂);支持2-10人...
透视脚本!wepoker辅助透... 透视脚本!wepoker辅助透视软件,pokemmo辅助官网,2025新版(竟然真的是有挂)1、不需...