处理 urllib2 的超时?

编程入门 行业动态 更新时间:2024-10-27 06:34:12
本文介绍了处理 urllib2 的超时?- Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

urllib2.urlopen('www.example', timeout=1)

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

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

有什么想法吗?

推荐答案

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

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("example", 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("example", 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 的超时?

本文发布于:2023-10-09 16:52:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476247.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!