处理 urllib2 的超时?- Python [英] Handling urllib2's timeout? - Python

查看:46
本文介绍了处理 urllib2 的超时?- Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 urllib2 的 urlopen 中使用超时参数.

I'm using the timeout parameter within the urllib2's urlopen.

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

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

How do I tell Python that if the timeout expires a custom error should be raised?

有什么想法吗?

推荐答案

在极少数情况下您要使用 ,除了:.这样做会捕获任何异常,这可能很难调试,并且它会捕获包括 SystemExitKeyboardInterupt 在内的异常,这会使您的程序烦人使用..

There are very few cases where you want to use 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..

最简单的情况是,您会发现 urllib2.URLError:

At the very simplest, you would catch 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)

这篇关于处理 urllib2 的超时?- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆