[英]Handling urllib2's return of badstatusline(line)?
I've got a simple internet checker running but it occasionally returns an error what I can't seem to handle... 我有一个简单的互联网检查器运行但它偶尔会返回一个我似乎无法处理的错误...
Here's the function: 这是功能:
def internet_on():
try:
urllib2.urlopen("http://google.co.uk/", timeout = 10)
return True
except urllib2.URLError as e:
return False
except socket.timeout as e:
return False
Here's the error: 这是错误:
Traceback (most recent call last):
File "C:/Testscript.py", line 117, in internet_on
urllib2.urlopen("http://google.co.uk/", timeout = 10)
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 442, in error
result = self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 629, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Python27\lib\urllib2.py", line 404, in open
response = self._open(req, data)
File "C:\Python27\lib\urllib2.py", line 422, in _open
'_open', req)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "C:\Python27\lib\urllib2.py", line 1187, in do_open
r = h.getresponse(buffering=True)
File "C:\Python27\lib\httplib.py", line 1045, in getresponse
response.begin()
File "C:\Python27\lib\httplib.py", line 409, in begin
version, status, reason = self._read_status()
File "C:\Python27\lib\httplib.py", line 373, in _read_status
raise BadStatusLine(line)
BadStatusLine: ''
How can I handle this error to return false, I'm wanting the internet_on function to return true if it connects but if anything other than true it should return false.. 如何处理此错误以返回false,我希望internet_on函数在连接时返回true但如果除了true之外还应返回false。
import httplib
...
def internet_on():
try:
urllib2.urlopen("http://google.co.uk/", timeout = 10)
return True
except (IOError, httplib.HTTPException):
return False
except httplib.BadStatusLine as e:
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.