在 argparse 中使用 Python 的 add_argument 时,如果调用特定的已弃用标志,如何抛出异常?

Jos*_*ong 5 python parsing action exception argparse

基本上想象我有一个有多个参数的argparser。我有一个特定的函数定义,如下所示:

    def add_to_parser(self, parser):
        group = parser.add_argument_group('')
        group.add_argument( '--deprecateThis', action='throw exception', help='Stop using this. this is deprecated')
Run Code Online (Sandbox Code Playgroud)

无论我是否可以尝试创建该操作来引发异常并停止代码,或者是否可以包装它以检查标志deprecateThis然后引发异常,我想知道如何做到这一点以及哪一个最好!谢谢。

Ibo*_*lit 2

这是我想出的:

您可以为您的参数注册自定义操作,我注册了一个来打印出弃用警告并从生成的命名空间中删除该项目:

class DeprecateAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        self.call_count = 0
        if 'help' in kwargs:
            kwargs['help'] = f'[DEPRECATED] {kwargs["help"]}'
        super().__init__(*args, **kwargs)


    def __call__(self, parser, namespace, values, option_string=None):
        if self.call_count == 0:
            sys.stderr.write(f"The option `{option_string}` is deprecated. It will be ignored.\n")
            sys.stderr.write(self.help + '\n')
            delattr(namespace, self.dest)
        self.call_count += 1


if __name__ == "__main__":
    my_parser = ArgumentParser('this is the description')
    my_parser.register('action', 'ignore', DeprecateAction)
    my_parser.add_argument(
        '-f', '--foo', 
        help="This argument is deprecated", 
        action='ignore')

    args = my_parser.parse_args()
    # print(args.foo)  # <- would throw an exception
Run Code Online (Sandbox Code Playgroud)