从自定义操作捕获ArgumentTypeError异常

从自定义操作捕获ArgumentTypeError异常

本文介绍了从自定义操作捕获ArgumentTypeError异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我自己的自定义操作中抛出ArgumentTypeError异常的最佳做法是什么,让argparse为我抓住它?

What is the best practice to throw an ArgumentTypeError exception from my own custom action and let the argparse to catch it for me?

似乎argparse的try / except块对我的自定义操作不处理此异常。虽然这样做对于内置的动作来说也是如此。

It seems that argparse's try/except block does not handle this exception for my custom actions. Though it does that just fine for its built-in actions.

class unique_server_endpoints(argparse.Action):
    """This class avoids having two duplicate OuterIPs in the client argument list"""
    def __call__(self, parser, namespace, values, option_string=None):
        ips = set()
        endpoints = []
        for r in values:
            ep = server_endpoint(r)
            if ep[0] in ips:
                raise argparse.ArgumentTypeError("Duplicate OuterIPs found")
            else:
                ips.add(ep[0])
                endpoints.append(ep)
        setattr(namespace, self.dest, endpoints)

group.add_argument('-c', "--client", nargs = 2,
            dest = "servers", action = unique_server_endpoints,

例如,在上面的代码中如果我会有重复的IP,那么异常会f全部到主要功能,并打印丑陋的堆栈跟踪。我不想要这个,我也不想在 main 中放入try / except块。

For example, in the code above If I would have duplicate IPs then the exception would fall down to the main function and print the ugly stacktrace. I don't want that and neither I don't want to put a try/except block inside main.

推荐答案

查看argparse源代码后,我发现它将ArgumentTypeError转换为ArgumentError异常。

After looking at argparse source code I figured out that it translates ArgumentTypeError to ArgumentError exception.

所以而不是:

            raise argparse.ArgumentTypeError("Duplicate OuterIPs found")

我应该有:

            raise argparse.ArgumentError(self, "Duplicate OuterIPs found")

和argparse仍然会为我做其他事情(捕获异常和打印使用消息)...

And argparse would still do the rest for me (catch exception and print usage message) ...

这篇关于从自定义操作捕获ArgumentTypeError异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:04