有没有办法为 FancyURLopener() 设置连接超时?我正在使用 FancyURLopener.retrieve() 下载文件,但有时它只是卡住了,仅此而已......我认为这是因为它仍在尝试连接并且不可能。那么有没有办法设置超时?
感谢您的每一个回复
如果要使用retrieve()
超时,可以在socket
模块中设置。
import socket
socket.setdefaulttimeout(5)
来源:http ://docs.python.org/py3k/howto/urllib2.html#sockets-and-layers
抱歉,解决了。我没有意识到我可以使用这样的东西......
fileName = string.split(url, '/')[-1]
data = urllib2.urlopen(url, timeout = 5) //Connection timeout set to 5 secs
newF = open(os.path.join(os.getcwd(), fileName), "wb")
newF.write(data.read())
newF.close()