Socket timeout exception exception

I would like to catch a socket timeout (preferably in an exception) ... except urllib.error.URLError: can catch it, but I need to distinguish between a dead link and a timeout .... If I except urllib.error.URLError: socket timeout does not break, and script fails with socket.timeout error

 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') 
+8
python timeout sockets
source share
1 answer
 ... except urllib.error.URLError, e: print type(e.reason) 

You will see <class 'socket.timeout'> whenever there is a socket timeout. Is this what you want?

For example:

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

All Articles