2013-06-22 95 views
4

我有一個簡單的互聯網檢查運行,但它偶爾會返回一個錯誤,似乎我無法處理......處理urllib2返回badstatusline(行)?

這裏的功能:

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 

這裏的錯誤:

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

我該如何處理這個錯誤返回false,我想讓internet_on函數返回true,如果它連接,但如果除true之外的任何東西,它應該返回false ..

回答

5
import httplib 

... 


def internet_on(): 
    try: 
     urllib2.urlopen("http://google.co.uk/", timeout = 10) 
     return True 
    except (IOError, httplib.HTTPException): 
     return False 
+0

是否覆蓋我的其他兩個部分(超時和urlerror)? – Ryflex

+0

'tiemout','URLError'是'IOError'的子類(直接/間接)。 – falsetru

+0

'BadStatusLine'是'HTTPException'的子類。 – falsetru

3
except httplib.BadStatusLine as e: 
    return False 
+0

這個和發佈的一個falsetru函數有什麼區別? – Ryflex

+1

Nothing - 如果要以不同的方式處理不同的異常,則可以使用單獨的except語句,但如果要對所有異常執行相同的操作,則可以按照@falsetru的方式將它們列入元組中。 – Amber