2010-04-26 90 views
53

我在urllib2的urlopen中使用了timeout参数。处理urllib2的超时? - Python

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

我该如何告诉Python,如果超时到期,应该提高自定义错误?


任何想法?

+1

注意:['timeout'参数既不会限制* total *连接时间也不会* total * read(响应)时间。](http://stackoverflow.com/a/32684677/4279) – jfs 2015-12-05 17:37:33

回答

87

有很少的情况下,你想使用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 – 2013-05-14 06:20:38

+0

@TalWeiss谢谢,为'socket.timeout'添加了一个额外的捕获 – dbr 2013-05-14 13:34:20

+1

至于Python 2.7.5超时被urllib2.URLError捕获。 – 2014-05-18 11:58:47

15

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