Catching ArgumentTypeError exception from custom a

2019-02-12 16:29发布

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

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)

and

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

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.

1条回答
叛逆
2楼-- · 2019-02-12 17:17

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

So instead of:

            raise argparse.ArgumentTypeError("Duplicate OuterIPs found")

I should have:

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

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

查看更多
登录 后发表回答