from urllib2 import urlopen, Request, HTTPError, URLError
url = "http://speedtest.website-solution.net/speedtest/random350x350.jpg"
try:
#f = urlopen(url, timeout=30) #never works - always times out
f = urlopen(url) #always works fine, returns after < 2 secs
print("opened")
f.close()
print("closed")
except IOError as e:
print(e)
pass
编辑:
进一步深入研究,它看起来更低......以下代码有相同的问题:
s = socket.socket()
s.settimeout(30)
s.connect(("speedtest.website-solution.net", 80)) #times out
print("opened socket")
s.close()
它在袜子代理后面运行。使用tsocks python test.py
运行。不知道是否由于某种原因可以搞砸套接字超时?似乎很奇怪,timeout=None
工作正常。
答案 0 :(得分:0)
好吧..弄清楚了。这确实与代理有关。不知道为什么,但以下代码似乎解决了它:
来源:https://code.google.com/p/socksipy-branch/
将其放在代码的开头:
import urllib2
from urllib2 import urlopen, Request, HTTPError, URLError
import httplib
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.56.1", 101)
socks.wrapmodule(urllib2)
现在一切正常......