Umgang mit urllib2 Rückkehr von badstatusline(Zeile)?

Habe ich eine einfache internet-checker laufen, aber es kommt gelegentlich eine Fehlermeldung zurück, was ich kann nicht scheinen zu umgehen...

Hier ist die Funktion:

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

Hier der Fehler:

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: ''

Wie kann ich das umgehen dieses Fehlers false zurück, ich wollte das internet_on Funktion gibt true zurück, wenn es verbindet, aber wenn etwas anderes als true es sollte false zurückgeben..

InformationsquelleAutor Ryflex | 2013-06-22
Schreibe einen Kommentar