我的问题很简单。
我有一个try/except
代码。在try中,我尝试了一些http请求,在except中,我有几种方法来处理得到的异常。
现在我想在代码中添加一个时间参数。这意味着尝试只会持续“n”秒。否则就用“除非”。
在自由语言中,它将显示为:
try for n seconds:
doSomthing()
except (after n seconds):
handleException()
这是中间代码。不是函数。我得抓紧时间处理。我不能就这样继续下去。
while (recoveryTimes > 0):
try (for 10 seconds):
urllib2.urlopen(req)
response = urllib2.urlopen(req)
the_page = response.read()
recoveryTimes = 0
except (urllib2.URLError, httplib.BadStatusLine) as e:
print str(e.__unicode__())
print sys.exc_info()[0]
recoveryTimes -= 1
if (recoveryTimes > 0):
print "Retrying request. Requests left %s" %recoveryTimes
continue
else:
print "Giving up request, changing proxy."
setUrllib2Proxy()
break
except (timedout, 10 seconds has passed)
setUrllib2Proxy()
break
我需要的解决方案是try (for 10 seconds)
以及except (timeout, after 10 seconds)
检查documentation
如果要捕获更多特定错误,请检查此post
或者请求
有关使用请求时出现异常的详细信息,请参见docs或此post
如果您使用的是UNIX,则为通用解决方案:
相关问题 更多 >
编程相关推荐