Python 2.6 之前版本中 urllib2.urlopen() 的超时 [英] timeout for urllib2.urlopen() in pre Python 2.6 versions

查看:32
本文介绍了Python 2.6 之前版本中 urllib2.urlopen() 的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

urllib2 文档 表示添加了 timeout 参数在 Python 2.6 中.不幸的是,我的代码库一直在 Python 2.5 和 2.4 平台上运行.

The urllib2 documentation says that timeout parameter was added in Python 2.6. Unfortunately my code base has been running on Python 2.5 and 2.4 platforms.

有没有其他方法可以模拟超时?我想要做的就是让代码在固定的时间内与远程服务器通话.

Is there any alternate way to simulate the timeout? All I want to do is allow the code to talk the remote server for a fixed amount of time.

也许有任何替代的内置库?(不想安装 3rd 方,比如 pycurl)

Perhaps any alternative built-in library? (Don't want install 3rd party, like pycurl)

推荐答案

您可以使用以下方法为所有套接字操作(包括 HTTP 请求)设置全局超时:

you can set a global timeout for all socket operations (including HTTP requests) by using:

socket.setdefaulttimeout()

像这样:

import urllib2
import socket
socket.setdefaulttimeout(30)
f = urllib2.urlopen('http://www.python.org/')

在这种情况下,您的 urllib2 请求将在 30 秒后超时并引发套接字异常.(这是在 Python 2.3 中添加的)

in this case, your urllib2 request would timeout after 30 secs and throw a socket exception. (this was added in Python 2.3)

这篇关于Python 2.6 之前版本中 urllib2.urlopen() 的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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