小编Vor*_*ura的帖子

在Python中使用isinstance检查特定类型的异常是否合理?

在Python中捕获泛型异常是否合理,然后用于isinstance()检测特定类型的异常以便正确处理它?

我现在正在使用dnspython工具包,它有一系列例外,例如超时,NXDOMAIN响应等等.这些例外是子类dns.exception.DNSException,所以我想知道它是否合理,或者是pythonic,以便捕获DNSException然后用isinstance().检查一个特定的例外.

例如

try:
    answers = dns.resolver.query(args.host)
except dns.exception.DNSException as e:
    if isinstance(e, dns.resolver.NXDOMAIN):
        print "No such domain %s" % args.host
    elif isinstance(e, dns.resolver.Timeout):
        print "Timed out while resolving %s" % args.host
    else:
        print "Unhandled exception"
Run Code Online (Sandbox Code Playgroud)

我是Python的新手,所以要温柔!

python exception-handling introspection dnspython

10
推荐指数
1
解决办法
6616
查看次数

为什么Python findall()和finditer()在unanchored.*搜索中返回空匹配?

对于Python文档findall()finditer()状态:

结果中包含空匹配,除非它们触及另一个匹配的开头

这可以证明如下:

In [20]: [m.span() for m in re.finditer('.*', 'test')]
Out[20]: [(0, 4), (4, 4)]
Run Code Online (Sandbox Code Playgroud)

谁能告诉我,为什么这个模式首先会返回一个空的匹配?不应该.*消耗整个字符串并返回单个匹配?而且,如果我将模式锚定到字符串的开头,为什么最后没有空匹配?例如

In [22]: [m.span() for m in re.finditer('^.*', 'test')]
Out[22]: [(0, 4)]
Run Code Online (Sandbox Code Playgroud)

python regex

8
推荐指数
1
解决办法
2994
查看次数