【发布时间】:2011-04-06 11:04:06
【问题描述】:
我正在使用Python's urllib2 发送 HTTP 帖子:
import socket, urllib, urllib2
socket.setdefaulttimeout(15)
postdata = urllib.urlencode({'value1' : 'a string', 'value2' : 'another string'})
headers = {
'User-Agent': 'Agent',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html, */*',
}
try:
request = urllib2.Request('http://www.example.com', postData, headers)
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
# Handle here
except urllib2.URLError, e:
# Handle here
except httplib.HTTPException, e:
# Handle here
有时网络问题会导致对 urlopen 的调用永远不会返回。我们看到 except 块正确处理了其他错误(包括超时)并调用了 socket.setdefaulttimeout() 但仍然存在 urlopen 永远不会返回的情况。
我知道它永远不会返回,因为我们的实际代码中有一些日志行在之前和之后被调用,当这个问题发生时,只有之前的调用才会被调用并且脚本永远挂起。
检测/处理此问题的最佳方法是什么?
【问题讨论】:
-
修改默认套接字超时对您不起作用吗?
-
我和你有同样的问题,你解决了吗?
标签: python sockets networking