Python - urllib2 timeout

[亡魂溺海] 提交于 2019-12-10 21:03:51

问题


I got something below is snippet of my code

opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
fetch_timeout = 12
self.response = opener.open(url, timeout=fetch_timeout)

however, it code still waits 60~ seconds before timing out... Any clues?


回答1:


At a guess you probably need to set the socket timeout

import socket

default_timeout = 12

socket.setdefaulttimeout(default_timeout)



回答2:


Which version are you using. It was added in 2.6

Also the method is

urllib2.urlopen(url[, data][, timeout])

Can you try providing

self.response = opener.open(url, None, fetch_timeout)

Yeah for all others, you could still use socket module to set socket time out.




回答3:


Look at the OpenerDirector class and the urllib2.install_opener() method.



来源:https://stackoverflow.com/questions/4207983/python-urllib2-timeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!