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..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With