处理urllib2的超时?-Python

2024-05-01 22:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

如何告诉Python,如果超时过期,则应引发自定义错误?


有什么想法吗?


Tags: orghttp参数examplewww错误timeouturllib2
2条回答

很少有情况下需要使用except:。这样做可以捕获任何异常,这可能很难调试,并且它捕获异常,包括SystemExitKeyboardInterupt,这可能使您的程序使用起来很烦人。。

最简单地说,您可以捕获^{}

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)

在Python2.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)

相关问题 更多 >