Python urllib2 - 连接暂时中断时冻结

Python urllib2 - Freezes when connection temporarily dies

所以,我正在使用 urllib2,它在特定页面上一直冻结。甚至 Ctrl-C 也不会取消操作。它没有抛出任何错误(我抓住了一切),而且我不知道如何打破它。 urllib2 是否有默认为从不的超时选项?

程序如下:

req = urllib2.Request(url,headers={'User-Agent':'...<chrome's user agent string>...'})
page = urllib2.urlopen(req)
// p.s. I'm not installing any openers

然后,如果互联网在第二行(下载它)中途中断,即使连接恢复,程序也会完全冻结。

这是我在浏览器 (Chrome) 中从同一页面获得的响应 header:

HTTP/1.1 200 OK
Date: Wed, 15 Feb 2017 18:12:12 GMT
Content-Type: application/rss+xml; charset=UTF-8
Content-Length: 247377
Connection: keep-alive
ETag: "00e0dd2d7cab7cffeca0b46775e1be7e"
X-Robots-Tag: noindex, follow
Link: ; rel="https://api.w.org/"
Content-Encoding: gzip
Vary: Accept-Encoding
Cache-Control: max-age=600, private, must-revalidate
Expires: Wed, 15 Feb 2017 18:12:07 GMT
X-Cacheable: NO:Not Cacheable
Accept-Ranges: bytes
X-Served-From-Cache: Yes
Server: cloudflare-nginx
CF-RAY: 331ab9e1443656d5-IAD

p.s。 url 是一个大型 WordPress 提要,根据响应,该提要看起来是压缩的。

虽然根据docs, the default timeout is, indeed, no timeout. You can specify a timeout when calling urlopen。 :)

page = urllib2.urlopen(req, timeout=30)