简体   繁体   English

处理urllib2的超时? - Python

[英]Handling urllib2's timeout? - Python

I'm using the timeout parameter within the urllib2's urlopen. 我在urllib2的urlopen中使用了timeout参数。

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

How do I tell Python that if the timeout expires a custom error should be raised? 如何告诉Python如果超时到期,应该引发自定义错误?


Any ideas? 有任何想法吗?

There are very few cases where you want to use except: . 除了以下情况之外,您想要使用的情况很少except: Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt , which can make your program annoying to use.. 这样做可以捕获任何难以调试的异常,并捕获包括SystemExitKeyboardInterupt在内的异常,这些异常会使您的程序使用起来很烦人。

At the very simplest, you would catch urllib2.URLError : 在最简单的情况下,你会捕到urllib2.URLError

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

The following should capture the specific error raised when the connection times out: 以下应捕获连接超时时引发的特定错误:

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)

In Python 2.7.3: 在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM