处理urllib2的超时?- Python

68

我正在使用urllib2的urlopen函数中的timeout参数。

urllib2.urlopen('http://www.example.org', timeout=1)

我应该如何告诉Python,如果超时就会引发自定义错误?


有什么想法吗?


2个回答

105

很少有情况需要使用except:。这样做会捕获所有异常,这可能很难调试,并且会捕获包括SystemExitKeyboardInterupt在内的异常,这可能会让你的程序使用起来很烦人。

最简单的情况是,您可以捕获urllib2.URLError:

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    raise MyException("There was an error: %r" % e)

当连接超时时,以下代码应该能够捕获特定的错误:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
    # For Python 2.6
    if isinstance(e.reason, socket.timeout):
        raise MyException("There was an error: %r" % e)
    else:
        # reraise the original error
        raise
except socket.timeout, e:
    # For Python 2.7
    raise MyException("There was an error: %r" % e)

5
在Python 2.7中这行代码无法运行,因为URLError已经无法捕获socket.timeout异常。 - Tal Weiss
@TalWeiss 谢谢,已添加了一个额外的socket.timeout捕获。 - dbr
2
对于Python 2.7.5,超时由urllib2.URLError捕获。 - Nicolas L
1
就此而言,使用Python 2.6.6时,连接超时似乎会导致urllib2.URLError。从缓慢服务器读取响应的超时似乎会导致socket.timeout。因此,总体来说,同时捕获这两种异常允许您区分这些情况。 - Kay
我正在使用Python 2.7,我刚刚用'urllib2.URLError'而不是'socket.timeout'来处理TimeoutException。 - lfvv
显示剩余2条评论

20

在Python 2.7.3版本中:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接