Catch socket timeout exception
I would like to catch the socket timeout (preferably in an exception) ... except urllib.error.URLError:
can catch it but I need to distinguished between a dead link and a timeout .... If I take out the except urllib.error.URLError:
the socket timeout does not catch and script terminates with an socket.timeout error
i开发者_StackOverflow中文版mport 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')
...
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'>
精彩评论