2011-08-23 101 views
8

我想趕上套接字超時(最好是一個例外)... except urllib.error.URLError:可以捕獲它,但我需要區分死鏈接和超時....如果我拿出except urllib.error.URLError:套接字超時沒有趕上和腳本在socket.timeout錯誤Catch套接字超時異常

import urllib.request,urllib.parse,urllib.error 
import socket 
import http 
socket.setdefaulttimeout(0.1) 


try: 
    file2 = urllib.request.Request('http://uk.geforce.com/html://') 
    file2.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13") 
    file3 = urllib.request.urlopen(file2).read().decode("utf8", 'ignore') 
except urllib.error.URLError: print('fail') 
except socket.error: print('fail') 
except socket.timeout: print('fail') 
except UnicodeEncodeError: print('fail') 
except http.client.BadStatusLine: print('fail') 
except http.client.IncompleteRead: print('fail') 
except urllib.error.HTTPError: print('fail') 

print('done') 

回答

5
... 
except urllib.error.URLError, e: 
    print type(e.reason) 

你會看到<class 'socket.timeout'>每當有一個套接字超時終止。這是你想要的嗎?

例如:

try: 
    data = urllib2.urlopen("http://www.abcnonexistingurlxyz.com") 
except Exception,e: 
    print type(e.reason) 
... 
<class 'socket.timeout'> 
+1

我才意識到你所標記的問題是Python的3.x的。不幸的是,我沒有訪問Python 3.上面的代碼應該適用於x> 3的2.x。 –