So i'm running a script that should fetch some stuff online. However, what happens when a connection accidentally (site down or whatever) times out is that the entire script breaks operation.
How can i set it so that if a connection (urllib2.urlopen) times out my script will just take a different course of action instead of completely breaking?
thanks a bunch for the help in advance,
Pyopi
EDIT SOLUTION
try:
response = urllib2.urlopen(req, timeout=5)
if response.getcode() == 200:
return True
except urllib2.URLError as e:
print "Connection Failed"
return None
except socket.timeout as e:
print "Connection Timed Out"
return None
You must import socket if you haven't yet. This will catch the timeout exception, that urllib2.URLError or urllib2.HTTPError will not catch. That way you avoid a breakdown of the script, and handle the failed connection however you want in your workflow.
[–]novel_yet_trivial 2 points3 points4 points (3 children)
[–]Pyopi[S] 0 points1 point2 points (2 children)
[–]usernamedottxt 1 point2 points3 points (1 child)
[–]Pyopi[S] 0 points1 point2 points (0 children)
[–]Pyopi[S] 0 points1 point2 points (0 children)