处理urllib2的超时? - Python

Rad*_*Hex 62 python timeout urllib urllib2

我在urllib2的urlopen中使用了timeout参数.

urllib2.urlopen('http://www.example.org', timeout=1)
Run Code Online (Sandbox Code Playgroud)

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


有任何想法吗?

dbr*_*dbr 99

您想要使用的情况非常少except:.这样做可以捕获任何难以调试的异常,并捕获包含SystemExit和的异常KeyboardInterupt,这可能会使您的程序使用起来很烦人.

在最简单的情况下,你会发现urllib2.URLError:

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

以下应捕获连接超时时引发的特定错误:

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)
Run Code Online (Sandbox Code Playgroud)

  • 这在Python 2.7中不起作用,因为URLError不再捕获socket.timeout (5认同)
  • 至于Python 2.7.5,urllib2.URLError会捕获超时. (2认同)

esh*_*han 19

在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)
Run Code Online (Sandbox Code Playgroud)