好吧,我在 google 和 stackoverflow 中搜索了这个答案,几个小时后没有看到一个正确的答案来做这个......
我在这里粘贴了 4 个假定的 python 工作脚本示例,用于为不存在的 url 设置默认超时,超时设置为套接字和/或超时参数。
没有人工作,所以永远不会触发超时。
有什么想法吗?
第一个例子:
import urllib2
try:
header_s = {"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
req = urllib2.Request("http://www.nonexistantdomainurl.com/notexist.php",headers = header_s)
print urllib2.urlopen(req, None, 5.0).read()
except urllib2.URLError, e:
print "Url Error: %r" % e
except Exception,e:
print "Fallo de tipo ",e
else:
print "all ok!"
第二个例子:
import urllib2
try:
response = urllib2.urlopen("http://www.nonexistantdomainurl.com/notexist.php", None, 2.5)
except urllib2.URLError, e:
print "Oops, timed out?"
第三个例子:
from urllib2 import Request, urlopen, URLError, HTTPError
import base64
req = Request('http://www.nonexistantdomainurl.com/notexist.php')
try:
response = urlopen(req,timeout=5.0)
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
第四个例子:
import urllib2
import socket
socket.setdefaulttimeout(5)
try:
response = urllib2.urlopen("http://www.faluquito.com/equipo.php",timeout=5.0).read()
except urllib2.URLError, e:
print "Url Error: %r" % e
最佳答案
>>> import urllib2
>>> import time
>>> import contextlib
>>>
>>> def timeit():
... s = time.time()
... try:
... yield
... except urllib2.URLError:
... pass
... print 'took %.3f secs' % (time.time() - s)
...
>>> timeit = contextlib.contextmanager(timeit)
>>> with timeit():
... r = urllib2.urlopen('http://loc:8080', None, 2)
...
took 2.002 secs
>>> with timeit():
... r = urllib2.urlopen('http://loc:8080', None, 5)
...
took 5.003 secs
关于python urllib2超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276243/